Rails Conditional Validation

后端 未结 2 1803
栀梦
栀梦 2021-01-06 03:15

So I have two models here:

class Screen < ActiveRecord::Base
  belongs_to :user
  validates :screen_size, :numericality =>{:less_than_or_equal_to =>         


        
2条回答
  •  伪装坚强ぢ
    2021-01-06 03:45

    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

提交回复
热议问题