I have an after_initialize method that I only want to call if I'm not updating a record. For example, something like the following:
after_initialize :set_some_name, :unless => :updating?
For example, Task.find(123).title
should call the after_initialize
method. Task.find(123).save!(:title => "something")
should not call the after_initialize
method.
Of course the "updating?" method doesn't exist in Rails. Is there an equivalent method or a way to do so?
I think you are looking for this method :
http://apidock.com/rails/ActiveRecord/Base/new_record%3F
In your after_initialize function, you can then check if the record has already been saved before doing your treatment.
Maybe
after_initialize :set_some_name, if: :new_record?
I solved it like so :)
after_initialize :set_alternative_title, :unless => :name_is_alternative_title?
def set_alternative_title
self.title = "Alternative title"
end
def name_is_alternative_title?
self.title == "Alternative title"
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.