Не могу обновить рельсы has_many: через отношения - PullRequest
0 голосов
/ 26 октября 2010

Я пытаюсь:

@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 голосов
/ 26 октября 2010

Вы пытаетесь обновить tag_id для всей коллекции @item.associations вместо обновления одного Assocation экземпляра.

Правильный способ решения этой проблемы зависит от того, чего вы пытаетесь достичь. Чтобы обновить tag_id для всех ассоциаций в @item.association, попробуйте:

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

Если вы хотите обновить идентификатор тега для конкретного 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])
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...