Noname
Noname

Reputation: 81

Provide default value for Model attribute

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?

Upvotes: 1

Views: 4371

Answers (2)

potashin
potashin

Reputation: 44581

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.

Upvotes: 6

Alejandro Marti
Alejandro Marti

Reputation: 113

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

Upvotes: 0

Related Questions