ruby on rails - accepts_nested_attributes_for and new records -


i'm using accepts_nested_attributes_for 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 "name" attribute. how can have accepts_nested_attributes_for not create new skill record if record same skill name exists?

you can avoid creating new skill validating skill name unique:

class skill < activerecord::base   validates_uniqueness_of :name end 

i guess want know though, how associate existing skill name have specified new user instead of creating new skill when 1 exists.

if trying suggests me attributes shouldn't nested @ all.

you before_save callback if wanted again, kind of defeats 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 

Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -