Rails 4: Difference between validates presence on id or association

前端 未结 1 1115
予麋鹿
予麋鹿 2021-01-11 15:56

If I have a \'belongs_to\' association in a model, I\'d like to know the notional difference between validating an association:

  class Topping  < ActiveR         


        
1条回答
  •  别那么骄傲
    2021-01-11 16:36

    Investigating further, I found that the 'presence' validator resolves to 'add_on_blank':

    http://apidock.com/rails/ActiveModel/Errors/add_on_blank

    def add_on_blank(attributes, options = {})
      Array(attributes).each do |attribute|
        value = @base.send(:read_attribute_for_validation, attribute)
        add(attribute, :blank, options) if value.blank?
      end
    end
    

    This does what it says: adds a validation error if the property in question is blank?

    This means it's simply an existence check. So if I validate an id, that id has to exist. That means:

    topping.pancake = Pancake.new
    topping.valid?
    

    would return false. However:

    topping.pancake_id = -12
    topping.valid?
    

    would return true. On the other hand, if I validate the object the exact opposite would be true. Unless -12 is a valid index, in which case ActiveRecord would automatically load it from the database on receipt of the 'pancake' message.

    Moving on to my issue, further investigation showed that blank? delegates to empty?, and indeed someone had defined empty? on the pancake, returning true if there are no toppings.

    Culprit found, and something about Rails learned.

    0 讨论(0)
提交回复
热议问题