本文介绍了Ruby on Rails的ActiveRecord的"的has_many:通过"唯一性验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前我通过插入每次检查的新的关系,如果它不存在:
除非Relationship.exists(:entry_id => entry.id,:tag_id => tag.id)?
我
如何才能实现关系模型中这样的验证,因此它不会允许有相同的进入和标签之间的多个关系?
解决方案
类关系<的ActiveRecord :: Base的
belongs_to的:进入
belongs_to的是:标签
验证:tag_id,分别:独特性=> {:范围=> :entry_id}
结束
Currently I insert a new relationship by everytime checking, if it doesn't exist:
unless Relationship.exists?(:entry_id => entry.id, :tag_id => tag.id)
How could I implement such validation inside the Relationship model, so that it wouldn't allow to have more than one relationship between the same entry and tag?
解决方案
class Relationship < ActiveRecord::Base
belongs_to :entry
belongs_to :tag
validates :tag_id, :uniqueness => { :scope => :entry_id }
end
这篇关于Ruby on Rails的ActiveRecord的&QUOT;的has_many:通过&QUOT;唯一性验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!