为模型属性提供默认值

Non*_*ame 1 activerecord ruby-on-rails rails-activerecord ruby-on-rails-5

我生成了一个包含以下字段的用户模型,user_identifier并且notification_time

rails g user user_identifier:string notification_time:string 
Run Code Online (Sandbox Code Playgroud)

现在我想将 设置notification_time为默认值17:00

什么是最好的方法来做到这一点?写回调?如果是,如何?

pot*_*hin 6

您可以使用before_save带条件的回调,例如:

before_save -> item { item. notification_time = "17:00" }, unless: :notification_time?
Run Code Online (Sandbox Code Playgroud)

您还可以attribute在 Rails 5 中使用:

attribute :notification_time, :string, default: "17:00"
Run Code Online (Sandbox Code Playgroud)

您还可以在您的数据库中设置一个默认值,但它似乎不是这种例程的灵活解决方案,因为如果您想更改该值,您将需要运行单独的迁移,而不仅仅是更改代码中的值。