无法更新rails has_many:通过关系

时间:2010-10-26 07:40:03

标签: ruby-on-rails

我试试:

@item.associations.update_attributes(:tag_id=>params[:tag])

@item.associations.tag_id=params[:tag]

两者分别为update_attributes和tag_id =提供了未定义的方法错误。这是我的设置:

class Item < ActiveRecord::Base
  has_many :associations,:foreign_key=>"item_id",:dependent=>:destroy
  has_many :reverse_associations,:foreign_key=>"tag_id",:class_name=>"Association"
  has_many :tags,:through=>:associations
end

class Tag < ActiveRecord::Base
  has_many :associations,:foreign_key=>"tag_id",:dependent=>:destroy
  has_many :reverse_associations,:foreign_key=>"item_id",:class_name=>"Association"
  has_many :items,:through=>:associations
  attr_accessible :name
end

class Association < ActiveRecord::Base
  belongs_to :item
  belongs_to :tag
end

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您尝试更新整个tag_id集合上的@item.associations,而不是更新单个Assocation实例。

解决这个问题的正确方法取决于你想要完成的任务。要更新tag_id中所有关联的@item.association,请尝试:

@item.associations.each do |association|
  association.update_attributes(:tag_id => params[:tag])
end

如果您想更新特定Association的标记ID,那么您需要首先获得该关联:

# Just picking the first association for the item as an example.
# You should make sure to retrieve the association that you actually
# want to update.
retagged_association = @item.associations.first

# Now, retag the association
retagged_association.update_attributes(:tag_id => params[:tag])