Rails 3 uniqueness validation with scope on polymorphic table

泪湿孤枕 提交于 2020-01-02 23:05:23

问题


I've got the following setup:

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

The Vote table looks like this:

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

I want to validate the following. A user with a given ip_address can only vote on 1 proposition. So the combination of ip_address, voteable_id and voteable_type needs to be unique.

How can i achieve this with a "simple" validation rule?


回答1:


To guarantee uniqueness you have to add unique index to your DB

If you don't have important data yet you can do it inside migration with add_index

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

in case you already have some data it can be done with SQL and it depends on your DBMS




回答2:


Add a scope to a unique :ip_address validation

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


来源:https://stackoverflow.com/questions/7794216/rails-3-uniqueness-validation-with-scope-on-polymorphic-table

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