2010-10-26 63 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