Reputation: 16584
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?
Upvotes: 2
Views: 115
Reputation: 7477
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
Upvotes: 1
Reputation: 13798
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
Upvotes: 1