当我尝试这样做时,joiner模型没有被保存(假设为Account has_many :users, through: :roles,反之亦然):
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这将创建@account,并在其中创建user_id=current_user.id和account_id: @account.id的角色记录。仅保存@account。角色模型中没有记录。使用console得到的结果是一致的。
在create操作中用current_user.accounts.create替换current_user.accounts.build,将保存joiner (角色记录)模型。因此,我不认为这是一个验证问题。我使用的是Rails 3.2.3。
型号:
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视图
<%= simple_form_for(@account) do |f| %>      
  <%= render 'account_fields', f: f %>
  <%= f.submit %>
<% end %>发布于 2012-05-19 01:53:16
发布于 2012-05-05 02:02:28
试着使用
更新:
class User < ActiveRecord::Base
  has_many :roles
  has_many :accounts, through: :roles, :autosave => true
endYou can find more info about autosave here。
或者在User模型中使用回调
after_save :save_accounts, :if => lambda { |u| u.accounts } 
def save_accounts 
  self.accounts.save
endhttps://stackoverflow.com/questions/10453346
复制相似问题