rails 3 : Do i need to give return true in a before_save callback for an object.save to work?

后端 未结 4 1884
伪装坚强ぢ
伪装坚强ぢ 2021-02-18 14:09
Class User  
  before_save :set_searchable

  def set_searchable  
    self.searchable = true if self.status == :active  
  end  
end  

>> u = User.last  
>>         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-18 14:36

    No, you don't need to return true from Rails callbacks. You can return nothing at all, or true, or 3.141592, and it will still be saved. The only thing that matters is if you return false, and this only applies prior to Rails 5. Returning false would cancel saving prior to Rails 5. Returning true never had any effect.

    For Rails 5+, the new way to block the update is to throw an exception: throw(:abort). . This is more intuitive and less error-prone. The return value has no effect on whether it will save, unless you configure legacy behaviour.

    It's valid - and imo good DRY practice - to just get on with your business and not return anything at all; just be sure to avoid accidentally returning false implicitly if using earlier Rails. For example:

    # This is fine, record will be saved
    def before_save
      self.foo = 'bar' # Implicitly returns 'bar'
    end
    
    # This is an accidental veto, record will not be saved
    def before_save
      Rails.logger.info 'user requested save'
      self.fresh = false # Oops! Implicitly returns false
    end
    
    # One way to rectify the above example (another would be to re-order if it's possible)
    def before_save
      Rails.logger.info 'user requested save'
      self.fresh = false
      return # Implicitly returns nil. Could also do `return true`
    end
    

    The gotcha here is that you might forget some "procedural" type functions will return a boolean as a kind of status code or simply because the implementation happens to end with a boolean as a side effect. You might think you're mutating a string or something, but end up accidentally vetoing the callback. So while I think it's usually too noisy to explicitly return from callbacks, you do need to take care with implicit returns. One reason people advocated returning true was to guard against this gotcha.

提交回复
热议问题