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.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
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