Rails 3唯一性验证与多态表上的范围

时间:2011-10-17 13:09:07

标签: ruby-on-rails-3 validation unique

我有以下设置:

class Vote < ActiveRecord::Base
  belongs_to :voteable, :polymorphic => :true, :counter_cache => true
end

class Proposition < ActiveRecord::Base
  has_many :votes, :as => :voteable
end

class Winner < ActiveRecord::Base
  has_many :votes, :as => :voteable
end

投票表如下所示:

t.string   "ip_address"
t.integer  "voteable_id"
t.string   "voteable_type"

我想验证以下内容。具有给定ip_address的用户只能对1个命题进行投票。因此,ip_address,voteable_id和voteable_type的组合必须是唯一的。

如何通过“简单”验证规则实现这一目标?

2 个答案:

答案 0 :(得分:3)

为了保证唯一性,您必须为数据库添加唯一索引

如果您还没有重要数据,则可以使用add_index

进行迁移
add_index(:votes, [:ip_address, :voteable_id, voteable_type], :unique => true, :name => 'allowed_one_vote')

如果您已经拥有一些数据,可以使用SQL完成,这取决于您的DBMS

答案 1 :(得分:3)

将范围添加到唯一的:ip_address验证

class Vote < ActiveRecord::Base
  # ...
  validates :ip_address, uniqueness: { scope: [:voteable_type, :voteable_id]}
end