开发者

accepts_nested_attributes_for and new records

I'm using accepts_nested_attributes_for with the following models:

User model:

class User < ActiveRecord::Base

  has_many :competences开发者_StackOverflow社区
  has_many :skills, :through => :competences, :foreign_key => :skill_id

  accepts_nested_attributes_for :skills
end

Skill model:

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

Competence model:

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

The Skill table has a "name" attribute. How can I have accepts_nested_attributes_for not create a new skill record if a record with the same skill name already exists?


You can avoid creating a new skill by validating the skill name to be unique:

class Skill < ActiveRecord::Base
  validates_uniqueness_of :name
end

I guess what you really want to know though, is how to associate the existing skill with the name they have specified to the new user instead of creating a new skill when one already exists.

If you are trying to do that it suggests to me that the attributes shouldn't actually be nested at all.

You could probably do it with a before_save callback if you really wanted to but again, it kind of defeats the purpose of nested attributes:

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


I think this question is answered here: accepts_nested_attributes_for with find_or_create?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜