On 1 May 2012 17:05, Mohamad El-Husseini <[email protected]> wrote: > I have User, Account, and Role models. The Account model accepts nested > properties for users. This way users can create their account and user > records at the same time. > > class AccountsController < ApplicationController > def new > @account = Account.new > @user = @account.users.build > end > end > > The above will work, but the user.roles.type defaults to member. At the time > of registration, I needuser.roles.type to default to admin. This does not > work: > > class AccountsController < ApplicationController > def new > @account = Account.new > @role = @account.role.build > # Role.type is protected; assign manually > @role.type = "admin" > @user = @account.users.build > end > end
It depends what you mean by 'work'. It will assign the type of @role to "admin" but the problem is that you have not saved it to the database after changing the type. By the way, I advise against using type as an attribute name, that is a reserved attribute name for use with STI. > ... > # user_id, account_id, type [admin|moderator|member] > class Role < ActiveRecord::Base > belongs_to :user > belongs_to :account > after_initialize :init > > ROLES = %w[owner admin moderator member] > > private > def init > self.role = "member" if self.new_record? > end > end Should that not be self.type (apart from the fact that type is not a good name)? But if you want a default value for a column why not just set the default in the database? Colin -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

