Accept_nested_attributes_for 和新记录
我将 Accepts_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
技能表有一个“名称”属性。如果已存在具有相同技能名称的记录,如何才能让 Accepts_nested_attributes_for 不创建新的技能记录?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过验证技能名称的唯一性来避免创建新技能:
我想您真正想知道的是如何将现有技能与他们为新用户指定的名称相关联,而不是在以下情况下创建新技能:一个已经存在。
如果您尝试这样做,它向我建议属性实际上根本不应该嵌套。
如果您确实愿意,您可能可以使用
before_save
回调来完成此操作,但同样,它又违背了嵌套属性的目的:You can avoid creating a new skill by validating the skill name to be unique:
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:我认为这个问题在这里得到了解答:accepts_nested_attributes_for with find_or_create?
I think this question is answered here: accepts_nested_attributes_for with find_or_create?