简体   繁体   中英

How do I set ActiveRecord model attribute when using .build method with Rails 3.2 (many-to-many)

I'm working on a sort of project management app with Rails (my Rails skills is kinda rusty). I have two model objects, in this case User and Account, which have a many-to-many relationship (Company could maybe be a better name for Account). When a user signs up a new Account is created (with.build) with help form a nested form. The Account model have two fields name and account_admin. When the the initial user creates it's Account I want to set account_admin to the users id. But I can't get this to work.

The models is set up like this:

class Account < ActiveRecord::Base
  attr_accessible :name, :account_admin

  validates_presence_of :name 

  has_many :projects, dependent: :destroy
  has_many :collaborators
  has_many :users, through: :collaborators
end 

class User < ActiveRecord::Base
  has_secure_password
  attr_accessible :email, :name, :password, :password_confirmation, :accounts_attributes

  has_many :collaborators
  has_many :accounts, through: :collaborators
  accepts_nested_attributes_for :accounts
  [...]

The UserController looks like this:

def new
  if signed_in?
    redirect_to root_path
  else
    @user = User.new
    # Here I'm currently trying to set the account_admin value, but it seems to be nil. 
    account = @user.accounts.build(:account_admin => @user.id)
  end
end  

I have also tried to move account = @user.accounts.build(:account_admin => @user.id) to the create action, but the the field disappears from the form.

What would be the appropriate way to accomplish what I want (set account_admin to the users id when it is getting created)? Or is there a better approach to find out which user created the account (ie. do something with the relationship table)?

Update

With help from @joelparkerhenderson I think I got it to work. I made a method in my User model that looks like this:

def set_account_admin
  account = self.accounts.last
  if account.account_admin == nil
    account.account_admin = self.id
    account.save
  end
end

Which I call with after_create:set_account_admin . This works, but is there a more "Rails way" to do the same?

Thanks.

When you call #new , the user doesn't have an id yet (it is nil).

When you #save the user, Rails automatically gives the user a new id.

You can then use the after_create Active Record callback to set the new Account's account_admin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM