【发布时间】:2015-08-01 18:27:28
【问题描述】:
我有一个投影模型来验证属性“ppr”的唯一性。我不想要多个投影记录,其中 :week、:player_id、:ppr 和 :created_at 年份都相同。 这里的关键问题是我不知道如何针对created_at 年份进行此验证。我不介意是否有多个记录,其中 :ppr、:player_id 和 :week 都是相同的,只要它们用于不同的 created_at 年份。
例如:
这是一个投影记录。
#<Projection id: 44, ppr: 3.5, salary: 6600, week: 1, created_at: "2014-09-04 06:05:34", player_id: 44>
如果我想创建这个额外的投影记录,即使 created_at 年份是 2015 年而不是 2014 年,我当前的验证也不允许这样做。
#<Projection id: 89, ppr: 3.5, salary: 6600, week: 1, created_at: "2015-09-05 06:05:34", player_id: 44>
我如何修改我的验证以解决这个额外的限制并允许来自不同年份的记录?
我基本上需要结合这两个验证:
validates_uniqueness_of :ppr, :scope => [:week, :player_id], :if => :nfl?
validates_uniqueness_of :ppr, conditions: { -> { where("created_at >= ? and created_at <= ?", "#{Date.today.year}0101", "#{Date.today.year}1231") } }
下面是我目前的模型设置方式:
class Projection < ActiveRecord::Base
attr_accessible :ppr, :salary, :score, :week, :player_id, :created_at
belongs_to :player
validates_uniqueness_of :ppr, :scope => [:week, :player_id], :if => :nfl?
scope :for_year, lambda {|year| where("created_at >= ? and created_at <= ?", "#{year}0101", "#{year}1231")}
end
更新
由于显而易见的原因,这种语法不起作用,但我可以做类似的事情吗?
validates_uniqueness_of :ppr, :scope, :created_at => [:week, :player_id, created_at <= ?", "#{Date.today.year}0101", "#{Date.today.year}1231"], :if => :nfl?
【问题讨论】:
标签: ruby-on-rails-3 validation