开发者

validate_presence_of fires before or after the call to before_save?

开发者 https://www.devze.com 2023-02-10 19:21 出处:网络
Does val_presence_of get called before the \'before_save\' event? how do I set a default value on a model\'s proper开发者_StackOverflow社区ty?Use before_validation callbacks:

Does val_presence_of get called before the 'before_save' event?

how do I set a default value on a model's proper开发者_StackOverflow社区ty?


Use before_validation callbacks:

class User
  before_validation(:on => :create) do
    self.time_zone ||= "Blah"
  end
end


Yes, all of your validations are run before the before_save callback is fired. For the complete list in order, see http://guides.rubyonrails.org/active_record_validations_callbacks.html#available-callbacks.

I would recommend using after_initialize. That's really what it's intended for. It means that it gets called for objects when they're loaded from the database, as well as when they're first created. In other words, their attributes are consistently what you expect them to be.

class User
  def after_initialization
    self.foobar ||= 'default value'
  end
end

From the docs:

The after_initialize callback will be called whenever an Active Record object is instantiated, either by directly using new or when a record is loaded from the database. It can be useful to avoid the need to directly override your Active Record initialize method.

The after_find callback will be called whenever Active Record loads a record from the database. after_find is called before after_initialize if both are defined.

The after_initialize and after_find callbacks are a bit different from the others. They have no before_* counterparts, and the only way to register them is by defining them as regular methods. If you try to register after_initialize or after_find using macro-style class methods, they will just be ignored. This behaviour is due to performance reasons, since after_initialize and after_find will both be called for each record found in the database, significantly slowing down the queries.

0

精彩评论

暂无评论...
验证码 换一张
取 消