der*_*use 1 activerecord model ruby-on-rails
我有一个模型如下:
class EntityTag < ActiveRecord::Base
attr_protected :user_id, :post_id, :entity_id
belongs_to :user
belongs_to :post
belongs_to :entity
validates :user_id, :presence => true
validates :entity_id, :presence => true
validates :post_id, :presence => true
end
Run Code Online (Sandbox Code Playgroud)
我想要防止具有user_id,entity_id和post_id的相同组合的多个行(例如,行的唯一ID是这些值中的所有三个).
我能与ActiveRecord沟通的最简单方法是什么?
正如@dhruvg所说:
validates_uniqueness_of :user_id, :scope => [:entity_id, :post_id]
Run Code Online (Sandbox Code Playgroud)
请注意,模型级别的唯一性验证不保证数据库中的唯一性.要有这个,你应该在你的表上放一个唯一的索引.
将以下内容添加到迁移中.
add_index :entity_tags, [:user_id, :post_id, :entity_id], :unique => true
Run Code Online (Sandbox Code Playgroud)