Rails 3 多态表范围的唯一性验证
我有以下设置:
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 的组合需要是唯一的。
我如何通过“简单”验证规则来实现这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了保证唯一性,您必须向数据库添加唯一索引。
如果您还没有重要数据,则可以使用 add_index
如果您已经有一些数据,可以使用 SQL 完成,这取决于您的 DBMS
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
in case you already have some data it can be done with SQL and it depends on your DBMS
将范围添加到唯一的
:ip_address
验证Add a scope to a unique
:ip_address
validation