Rails Conditional Validation

后端 未结 2 1805
栀梦
栀梦 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:32

    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
    

提交回复
热议问题