krn*_*krn 13 activerecord ruby-on-rails
目前我每次检查都会插入一个新关系,如果它不存在:
unless Relationship.exists?(:entry_id => entry.id, :tag_id => tag.id)
Run Code Online (Sandbox Code Playgroud)
我如何在关系模型中实现这样的验证,以便它不允许在同一条目和标记之间有多个关系?
fl0*_*00r 23
class Relationship < ActiveRecord::Base
belongs_to :entry
belongs_to :tag
validates :tag_id, :uniqueness => { :scope => :entry_id }
end
Run Code Online (Sandbox Code Playgroud)
假设您的模型看起来像这样:
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
Run Code Online (Sandbox Code Playgroud)
您可以为Relationship
连接模型添加唯一验证:
validates_uniqueness_of :tag_id, :scope => :entry_id
Run Code Online (Sandbox Code Playgroud)
该validates_uniqueness_of
方法将确保关系尚不存在,并且该:scope
选项将匹配范围限定为给定列.rails通过此验证生成的SQL将如下所示:
SELECT `relationships`.id
FROM `relationships`
WHERE (`relationships`.`tag_id` = <tag id> AND `relationships`.`entry_id` = <entry id>)
LIMIT 1
Run Code Online (Sandbox Code Playgroud)
(您会注意到它与您明确使用的SQL生成的SQL基本相同Relationship.exists?(:entry_id => entry.id, :tag_id => tag.id)
),如果找到记录,验证将失败.
同样,与您要验证唯一性的任何情况一样,请确保tag_id, entry_id
您的relationships
表中有唯一键.有关详细信息,请参阅此文章以及我上面链接的API页面的"并发性和完整性".
归档时间: |
|
查看次数: |
8213 次 |
最近记录: |