The joiner model is not being saved when I try this (assumingAccount has_many :users, through: :roles and vice-versa):
def new
@account = current_user.accounts.build
end
def create
@account = current_user.accounts.build(params[:account])
@account.save # does not save the joiner model
end
That should create @account, and a Role record where user_id=current_user.id and account_id: @account.id. Only @account gets saved. There are not records in the Role model. The results are consistent using console.
Replace current_user.accounts.build with current_user.accounts.create in the create action, the joiner (role record) model gets saved. For this reason I don’t think this is a validation issue. I’m using Rails 3.2.3.
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
attr_accessible
belongs_to :users
belongs_to :accounts
end
View
<%= simple_form_for(@account) do |f| %>
<%= render 'account_fields', f: f %>
<%= f.submit %>
<% end %>
This is a bug: https://github.com/rails/rails/issues/6161#issuecomment-5631018