I try:
@item.associations.update_attributes(:tag_id=>params[:tag])
and
@item.associations.tag_id=params[:tag]
Both give me undefined method errors for update_attributes and tag_id=, respectively. Here's my setup:
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
belong开发者_如何学Pythons_to :item
belongs_to :tag
end
What am I doing wrong?
You're trying to update tag_id
on the entire @item.associations
collection instead of updating a single Assocation
instance.
The proper way to solve this depends on what you're trying to accomplish. To update the tag_id
for all associations in @item.association
, try:
@item.associations.each do |association|
association.update_attributes(:tag_id => params[:tag])
end
If you want to update the tag id for a specific Association
, then you somehow need to get that association first:
# 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])
精彩评论