【发布时间】:2011-04-15 08:17:18
【问题描述】:
如何在 has_many :through 关联中使用 ActiveRecord 的accepts_nested_attributes_for 助手,同时将属性添加到连接表?
例如,假设我有一个团队模型:
class Team < ActiveRecord::Base
role = Role.find_by_name('player')
has_many :players,
:through => :interactions,
:source => :user,
:conditions => ["interactions.role_id = ?", role.id] do
class_eval do
define_method("<<") do |r|
Interaction.send(:with_scope, :create => {:role_id => role.id}) { self.concat r }
end
end
end
end
团队有_many players 到interactions,因为一个用户可以担任多个角色(玩家、经理等)。
如何在使用accepts_nested_attributes_for 的同时向连接表添加属性?
如果我有一个现有的团队记录 team 和一个现有的用户记录 user,我可以这样做:
team.players << user
team.players.size
=> 1
但如果我创建一个包含嵌套玩家的新团队:
team = Team.create(:name => "New York Lions",
:players_attributes => [{:name => 'John Doe'}])
team.players.size
=> 0
在最后一个示例中,创建了团队、用户和交互记录(并且团队确实通过交互拥有用户),但未在此处设置 interaction.role_id 属性。
【问题讨论】:
-
您解决了这个问题吗?
-
您的问题的答案可以在这篇文章中找到:stackoverflow.com/questions/2182428/…
标签: ruby-on-rails activerecord