views:

33

answers:

2

I want to create user-specific validations.

User has a column called "rule_values" which is a serialized hash of certain quantities.

In a separate model, Foo, I have a validation:

class Foo < ActiveRecord::Base
  belongs_to :user

  n = self.user.rule_values[:max_awesome_rating] #this line is giving me trouble!
  validates_presence_of :awesome_rating, :in => 1..n
end

It seems that self refers to Foo (which is why I'm getting an undefined method error) and not an instance of Foo. How can I access the User instance from within the Foo model?

+1  A: 

How about creating a custom validation on Foo something like this?

class Foo < ActiveRecord::Base

  validate do |foo|
    n = foo.user.rule_values[:max_awesome_rating]
    unless (1..n).include? foo.awesome_rating
      foo.errors.add :awesome_rating, "must be present and be between 1 and #{n}"
    end
  end

end

This way you have access to the instance and the user association

bjg
bonus points for using a block. nice work, everyone! thanks!
+1  A: 

Rails supports custom validations (using validate). Here's an idea of how it might work (did not check it though):

class Foo < ActiveRecord::Base
  belongs_to :user
  validate :awesome_rating_is_in_range

  def awesome_rating_is_in_range
    errors.add(:awesome_rating, 'not in range') unless (1..user.rule_values[:max_awesome_rating]).include? awesome_rating
  end
end
Flavius Stef