【问题标题】:ruby on rails specifying uniqueness in db across multiple columnsruby on rails 在多列中指定 db 中的唯一性
【发布时间】:2011-06-01 05:10:16
【问题描述】:

我有一个模型如下:

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

我想防止多行具有相同的 user_id、entity_id 和 post_id 组合(例如,一行的唯一 ID 是所有这三个值)。

与 ActiveRecord 交流的最简单方法是什么?

【问题讨论】:

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

标签: ruby-on-rails activerecord model


【解决方案1】:

正如@dhruvg 提到的:

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

请注意,模型级别的唯一性验证并不能保证数据库中的唯一性。为此,您应该在表上放置一个唯一索引。

将以下内容添加到您的迁移中。

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

【讨论】:

    【解决方案2】:

    我会在控制器的 create 操作中检查这一点。

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

    将返回具有相同值的任何现有记录的Array。如果是Array.count == 0,那么可以继续正常保存新创建的对象。否则,您可以返回现有记录或抛出错误;这取决于你。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-05
      • 2021-07-04
      • 2013-02-03
      • 2010-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多