2010-10-26 46 views
0

我尝试:无法更新导轨的has_many:通过关系

@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 

我在做什么错?

回答

0

您正试图在整个@item.associations集合上更新tag_id而不是更新单个Assocation实例。

解决这个正确的方法取决于你要完成的任务。要更新tag_id所有协会@item.association,尝试:

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

如果要更新标签ID特定Association,那么你就莫名其妙需要首先得到该协会:

# 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]) 
+0

哦。 “咄”那一刻,我...现在只有一个该项目的关联,所以我想这并没有发生在我身上。 – herpderp 2010-10-26 09:03:13

+0

当然,现在我才意识到,更新关联甚至没有必要,我可以只创建/根据需要摧毁。 – herpderp 2010-10-26 09:15:52