1

我将 Accept_nested_attributes_for 与以下模型一起使用:

用户型号:

class User < ActiveRecord::Base

  has_many :competences
  has_many :skills, :through => :competences, :foreign_key => :skill_id

  accepts_nested_attributes_for :skills
end

技能模型:

class Skill < ActiveRecord::Base
  has_many :competences
  has_many :users, :through => :competences, :foreign_key => :user_id
end

能力模型:

class Competence < ActiveRecord::Base
  belongs_to :user
  belongs_to :skill
end

技能表有一个“名称”属性。如果已经存在具有相同技能名称的记录,我如何才能让 accept_nested_attributes_for 不创建新的技能记录?

4

2 回答 2

0

您可以通过验证技能名称的唯一性来避免创建新技能:

class Skill < ActiveRecord::Base
  validates_uniqueness_of :name
end

我想您真正想知道的是,如何将现有技能与他们为新用户指定的名称相关联,而不是在已有技能时创建新技能。

如果您尝试这样做,它会向我建议属性实际上根本不应该嵌套。

before_save如果您真的想这样做,您可能可以通过回调来做到这一点,但同样,它有点违背了嵌套属性的目的:

class User << ActiveRecord::Base
  before_save :check_for_existing_skill
  def check_for_existing_skill
    if self.skill
      existing_skill = Skill.find_by_name(self.skill.name)
      if existing_skill
        self.skill = existing_skill
      end
    end
  end
end
于 2010-10-07T12:12:15.737 回答
0

我认为这个问题在这里得到了回答:accepts_nested_attributes_for with find_or_create?

于 2011-02-25T02:00:15.690 回答