samedi 1 août 2015

Rails 3 validates_uniqueness_of for two model attributes AND created_at year

I have a Projection model which validates the uniqueness of the attribute "ppr". I do not want multiple Projection records where the :week, :player_id, :ppr, AND :created_at year are all the same. The key problem here is that I do not know how to make this validation specific for the created_at year. I don't mind if there are multiple records where :ppr, :player_id, and :week are all the same as long as they are for different created_at years.

For example:

Here is a Projection record.

 #<Projection id: 44, ppr: 3.5, salary: 6600, week: 1, created_at: "2014-09-04 06:05:34", player_id: 44> 

If I want to create this additional Projection record my current validation will not allow it even though the created_at year is 2015 and not 2014.

#<Projection id: 89, ppr: 3.5, salary: 6600, week: 1, created_at: "2015-09-05 06:05:34", player_id: 44> 

How do I modify my validation to account for this additional constraint and allow records from a different year?

I basically need to combine these two validations:

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") } }

Posted below is how I currently have my model setup:

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

UPDATE

This syntax didn't work for obvious reasons but can I do something similar to this?

validates_uniqueness_of :ppr, :scope, :created_at => [:week, :player_id, created_at <= ?", "#{Date.today.year}0101", "#{Date.today.year}1231"], :if => :nfl?

Aucun commentaire:

Enregistrer un commentaire