简体   繁体   English

Ruby on Rails ActiveRecord“ has_many:through”唯一性验证

[英]Ruby on Rails ActiveRecord “has_many :through” uniqueness validation

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? 如何在Relationship模型中实现这种验证,以免同一条目和标签之间不止一个关系?

class Relationship < ActiveRecord::Base
  belongs_to :entry
  belongs_to :tag
  validates :tag_id, :uniqueness => { :scope => :entry_id }
end

Assuming your models look something like this: 假设您的模型如下所示:

class Entry < ActiveRecord::Base
  has_many :relationships
  has_many :tags, :through => :relationships
end

class Tag < ActiveRecord::Base
  has_many :relationships
  has_many :entries, :through => :relationships
end

class Relationship < ActiveRecord::Base
  belongs_to :entry
  belongs_to :tag
end

You could add a unique validation to your Relationship join model: 您可以向“ Relationship连接模型添加唯一的验证:

validates_uniqueness_of :tag_id, :scope => :entry_id

The validates_uniqueness_of method will ensure that the Relationship doesn't already exist, and the :scope option will scope the match to the given column. validates_uniqueness_of方法将确保Relationship不存在,并且:scope选项会将匹配范围限定在给定的列。 The SQL generated by rails via this validation will look like: rails通过此验证生成的SQL如下所示:

SELECT `relationships`.id
FROM `relationships`
WHERE (`relationships`.`tag_id` = <tag id> AND `relationships`.`entry_id` = <entry id>)
LIMIT 1

(which you'll notice is essentially the same SQL generated by your explicit use of Relationship.exists?(:entry_id => entry.id, :tag_id => tag.id) ), and if a record is found, validation will fail. (您会注意到,这与您显式使用Relationship.exists?(:entry_id => entry.id, :tag_id => tag.id)生成的SQL相同Relationship.exists?(:entry_id => entry.id, :tag_id => tag.id) ),如果找到记录,验证将失败。

As well, as with any case where you want to validate uniqueness, ensure that you have a unique key on tag_id, entry_id in your relationships table. 同样,与要验证唯一性的任何情况一样,请确保在relationships表中的tag_id, entry_id上具有唯一键。 See this article and the "Concurrency and integrity" of the API page I linked above for more info. 有关更多信息,请参见本文和我上面链接的API页面的“并发性和完整性”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM