ruby on rails specifying uniqueness in db across multiple columns

 ̄綄美尐妖づ 提交于 2019-12-09 23:45:29

问题


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 can communicate that to ActiveRecord?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/6196560/ruby-on-rails-specifying-uniqueness-in-db-across-multiple-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!