Conditional Rails Validation

So, I have two models:

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 does not work, because no matter what value user.access has, it will still check. What am I doing wrong here?

thank

+5
source share
2 answers

changes:

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

with:

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

Because:

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

  • if there is no user on your screen, it screen.user.accesswill simply throw an exception

+21
source

You passed the string to: if the exec parameter is proc / function. When it is a string, it tries to find a function with this name. What you really want is an anonymous function using 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
+1
source

All Articles