Rails 3 唯一性验证与多态表上的范围 [英] Rails 3 uniqueness validation with scope on polymorphic table

查看:44
本文介绍了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 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

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

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')

如果你已经有了一些数据,它可以用 SQL 来完成,这取决于你的 DBMS

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

这篇关于Rails 3 唯一性验证与多态表上的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆