将现有记录添加到has_many:通过关系

时间:2012-12-01 00:03:54

标签: ruby-on-rails activerecord has-many-through

我正在构建一个字典应用程序,其中我使用连接模型将一些概念链接到某些单词。我有一个表单来编辑每个概念,我可以在其中编辑单词,为其添加新单词或将现有单词与其关联。

我正在使用accepts_nested_attributes_forupdate_attributes,但这仅适用于已经关联的字词或新创建的字词。对于之前未关联的现有单词,当ActiveRecord在连接模型上运行select时,我会收到类似ActiveRecord::RecordNotFound (Couldn't find Word with ID=4 for Concept with ID=1000)的错误。

以下是我的模特:

class Word < ActiveRecord::Base
  attr_accessible :notes, :text, :grammar_tag_list

  has_many :semantic_relations, :dependent => :destroy
  has_many :concepts, :through => :semantic_relations
end

class Concept < ActiveRecord::Base
  attr_accessible :meaning_tag_list, :words_attributes

  has_many :semantic_relations, :dependent => :destroy
  has_many :words, :through=> :semantic_relations, :order => 'knowledge_id ASC'

  accepts_nested_attributes_for :words, :reject_if => lambda { |w| w[:text].blank? }
end

class SemanticRelation < ActiveRecord::Base
  belongs_to :word, :inverse_of => :semantic_relations
  belongs_to :concept, :inverse_of => :semantic_relations
end

我已经在我的Concepts控制器中使用以下方法管理它(在update_attributes之前调用它),但它似乎是一种非常脏的方法。有没有正确的方法来实现这个目标?

def check_words
  current_ids = @concept.word_ids
  new_ids = params[:concept][:words_attributes].map do |w|
    id = w[1][:id].to_i
    unless id == 0
      unless current_ids.include? id
        id
      end
    end
  end
  @concept.word_ids = current_ids + new_ids unless new_ids.blank?
end

0 个答案:

没有答案
相关问题