5

So I have two models here:

class Screen < ActiveRecord::Base
  belongs_to :user
  validates :screen_size, :numericality =>{:less_than_or_equal_to =>100,:greater_than_or_equal_to => 0},:if => "user.access==1"

class User < ActiveRecord::Base
  has_many :screens
  attr_accessible :access

But this code doesn't work, cause no matter what value the user.access is, it will still execute the validation. What am I doing wrong here?

Thank you

apneadiving
  • 114,565
  • 26
  • 219
  • 213
zsljulius
  • 3,813
  • 8
  • 36
  • 61

2 Answers2

21

change:

:if => "user.access==1"

with:

:if => lambda { |screen| screen.user.try(:access) ==1 }

Because:

  • you need to pass a function to evaluate condition on the fly

  • if your screen doesn't have any user, a mere screen.user.access would throw an exception

apneadiving
  • 114,565
  • 26
  • 219
  • 213
  • 5
    I would go with the proc as well, but by [the docs](http://guides.rubyonrails.org/active_record_validations_callbacks.html#using-a-string-with-if-and-unless), it should accept a string to evaluate in the scope of the saved record. I wonder if `self.user.try(:access) == 1` would work? – numbers1311407 Sep 05 '11 at 19:38
1

You passed in a string to the :if executable proc/function parameter. When this is a string, it tries to find a function with that name. What you actually want is an anonymous function here using a lambda.

class Screen < ActiveRecord::Base
  belongs_to :user
  validates :screen_size, :numericality => {:less_than_or_equal_to =>100, :greater_than_or_equal_to => 0}, :if => lambda {|s| s.user.access == 1 }
end

class User < ActiveRecord::Base
  has_many :screens
  attr_accessible :access
end
Winfield
  • 18,985
  • 3
  • 52
  • 65
  • 2
    According to [the docs](http://guides.rubyonrails.org/active_record_validations_callbacks.html#using-a-string-with-if-and-unless), this is untrue for Rails 3 (I can't remember if it was the case in 2). A symbol would refer to a method, a string is evaluated in the scope of the record. – numbers1311407 Sep 05 '11 at 19:44