1

I generated a user model with the following fields user_identifier and notification_time:

rails g user user_identifier:string notification_time:string 

Now I would like to set the notification_time to a default value that would be to 17:00

What would be the best way to do this? writing a callback? If yes, how?

potashin
  • 44,205
  • 11
  • 83
  • 107
Noname
  • 91
  • 3
  • 11
  • Do you want to have this default in the database perhaps even with protection against `null` values? Do you want existing records to be updated as well? Or don't you care about consistency on a database level and an update before save might be enough? – spickermann Jul 25 '18 at 10:42

2 Answers2

6

You can use a before_save callback with condition, for example:

before_save -> item { item. notification_time = "17:00" }, unless: :notification_time?

You can also use attribute in Rails 5:

attribute :notification_time, :string, default: "17:00"

You can also set a default value in your db, but it doesn't seem to be a flexible solution for this kind of routine, cause in case you wanted to change the value you would need to run a separate migration instead of just changing the value in your code.

potashin
  • 44,205
  • 11
  • 83
  • 107
0

You can check this How do I create a default value for attributes in Rails activerecord's model?

Basically you'll have to run a migration

add_column :users, :notification_time, :string, default: "17:00"

or, as you say, use a callback

before_save :default_values
  def default_values
    self.notification_time ||= "17:00"
  end
Alejandro Marti
  • 113
  • 1
  • 6
  • Thanks :) an add on question: should notification_time be set as "rails g model notification_time:time" or as a string? – Noname Jul 25 '18 at 13:53
  • Good question. Indeed, postgres can handle notification_time:time with the hh:mm format. Then you can perform queries like Model.where("notification_time > '10:00:00'") – Alejandro Marti Jul 27 '18 at 22:18