How to - before_save :set_something, on: :create

I’d like to set the lesson_date on a Lesson to Date.current when the lesson record is first created. It should not be changed after creation.

I hacked it together at the start using a hidden field on the new_lesson form but I want to move it to the model instead.

I thought the following would do the trick but it’s being called after creation too:

before_save :set_lesson_date, on: :create

What’s the correct before_filter for achieving this?

I’m on Rails 3.2.14 and ruby 1.9.3p448

Hi @weavermedia,

I’m not sure I understand the problem, but it seems that you only want to set the lesson date for new objects. If so, you can use before_save :set_lesson_date, if: :new_record?

However, if you are in a position to avoid the use of callbacks, I would recommend you’d do.
Lately I’ve come to see callbacks with conditionals as somewhat of a code smell and refactor them to use a method wrapping ActiveRecord calls. A simplified example:

class Lesson < ActiveRecord::Base

 def self.create_with_date(params)
   create(
     attribute: params[:blah],
     lesson_date: Date.current,
   )
 end
end

You might also want to consider if Date.current is what you need. I believe Date uses the server’s time, so you might want Time.zone.now (which uses the application’s time zone).

Hope this helps :slight_smile:

3 Likes

I second this.

1 Like

Thanks @pedromoreira and @benorenstein for the info.

I changed to if: :new_record? right away and it fixed the issue.

I’ll move over to a custom create method when I get some refactoring time, sounds like a great idea. I really like how it completely encapsulates the setting of lesson_date inside a very explicit method.