views:

31

answers:

1

Hi, I'm using accepts_nested_attributes_for with the following models:

User model:

class User < ActiveRecord::Base

  has_many :competences
  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?

A: 

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
Shadwell