【问题标题】:Rails 3 uniqueness validation with scope on polymorphic tableRails 3 在多态表上的唯一性验证
【发布时间】:2011-10-17 13:09:06
【问题描述】:

我有以下设置:

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的组合需要是唯一的。

如何使用“简单”的验证规则来实现这一点?

【问题讨论】:

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


    【解决方案1】:

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

    如果您还没有重要数据,您可以使用 add_index 在迁移中进行操作

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

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

    【讨论】:

    • 性能好不好由你自己决定
    • 这不能回答问题。提问者想要一个验证。如果确实没有针对这种情况的特定验证,那么答案就是进行自定义验证。这可能是也可能不是“最好”的方式(取决于具体情况),但是做一个 DB 约束和一个验证是苹果和橘子。
    【解决方案2】:

    为唯一的:ip_address 验证添加范围

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

    【讨论】:

      猜你喜欢
      • 2011-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多