开发者

ruby on rails specifying uniqueness in db across multiple columns

I have a model as follows:

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

I want to guard against multiple rows which have the same combination of user_id, entity_id, and post_id (e.g. a unique ID for a row is all three of those values).

What's the easiest way I c开发者_运维知识库an communicate that to ActiveRecord?


As @dhruvg mentioned:

validates_uniqueness_of :user_id, :scope => [:entity_id, :post_id]

Do note that uniqueness validation on model level does NOT guarantee uniqueness in the DB. To have that, you should put a unique index on your table.

Add the following to your migrations.

add_index :entity_tags, [:user_id, :post_id, :entity_id], :unique => true


I would check for this in the create action of your controller.

EntityTag.where(["user_id = ? and entity_id = ? and post_id = ?",
  params[:user_id], params[:entity_id], params[:post_id]]).all

will return an Array of any existing record that have those same values. If Array.count == 0, then you can continue to save the newly created object as normal. Otherwise you can either return the existing record or throw an error; it's up to you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜