Rails 3 uniqueness validation with scope on polymorphic table
I've got the following setup:
class Vote < A开发者_StackOverflow中文版ctiveRecord::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?
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
Add a scope to a unique :ip_address
validation
class Vote < ActiveRecord::Base
# ...
validates :ip_address, uniqueness: { scope: [:voteable_type, :voteable_id]}
end
精彩评论