Why does Rails only save the joiner record in one instance but not another?

8 views
Skip to first unread message

Mohamad El-Husseini

unread,
May 4, 2012, 10:00:07 AM5/4/12
to rubyonra...@googlegroups.com
Assuming we have User, Account, and Role models, and a User has_many :accounts, through: :roles and vice-versa, with the following snippet Rails automatically creates the Role (joiner) record, but with the snippet after Rails will not. I think I'm misunderstanding how has_many through works, so I would appreciate any insight into the subject.
 
def new
 
@account = Account.new(params[:account])
 
@user    = @account.users.build
end
def new
 
@account = Account.new(params[:account])
 
@account.save
end
Using this snippet Rails does not save the Role record: (If you replace current_user.accounts.build with current_user.accounts.create Rails will save the Role record)

def new
 
@account = current_user.accounts.build
end
def create
 
@account = current_user.accounts.build(params[:account])
 
@account.save
end
Models:
class User < ActiveRecord::Base
  has_many
:roles
  has_many
:accounts, through: :roles
end
class Account < ActiveRecord::Base
  has_many
:roles
  has_many
:users, through: :roles
  accepts_nested_attributes_for
:users
end
class Role < ActiveRecord::Base
  belongs_to
:users
  belongs_to
:accounts
end
Reply all
Reply to author
Forward
0 new messages