Ruby on rails 接受通过连接表的\u嵌套的\u属性\u以及连接表上的属性

Ruby on rails 接受通过连接表的\u嵌套的\u属性\u以及连接表上的属性,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,在向联接表添加属性时,如何在has\u many:through关联中使用ActiveRecord的accepts\u嵌套的\u attributes\u作为辅助对象 例如,假设我有一个团队模型: class Team < ActiveRecord::Base role = Role.find_by_name('player') has_many :players, :through => :interactions,

在向联接表添加属性时,如何在has\u many:through关联中使用ActiveRecord的accepts\u嵌套的\u attributes\u作为辅助对象

例如,假设我有一个团队模型:

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
但如果我创建了一个新团队,其中有一个嵌套的玩家:

team = Team.create(:name => "New York Lions", 
                   :players_attributes => [{:name => 'John Doe'}])
team.players.size
=> 0
在最后一个示例中,创建了团队、用户和交互记录(团队确实通过交互拥有用户),但此处未设置interactions.role\u id属性。

class teamclass Team < ActiveRecord::Base
  accepts_nested_attributes_for :interactions

class Interaction < ActiveRecord::Base
  accepts_nested_attributes_for :players


team = Team.create(:name => "New York Lions", :interactions_attribues => [{
                   :players_attributes => [{:name => 'John Doe'}]}])
接受\u嵌套的\u属性\u用于:交互 类交互“纽约狮子会”,:interactions\u attributes=>[{ :players_attributes=>[{:name=>'johndoe'}]}])
我没有检查创建,所以数组和散列可能有点混乱,但你明白了。您需要团队和交互模型上的accepts_nested_属性。

您解决过这个问题吗?您的问题的答案可以在以下帖子中找到:
class Team < ActiveRecord::Base
  accepts_nested_attributes_for :interactions

class Interaction < ActiveRecord::Base
  accepts_nested_attributes_for :players


team = Team.create(:name => "New York Lions", :interactions_attribues => [{
                   :players_attributes => [{:name => 'John Doe'}]}])