Rails:如何为 Rails activerecord 模型中的属性创建默认值? [英] Rails: How do I create a default value for attributes in Rails activerecord's model?

查看:29
本文介绍了Rails:如何为 Rails activerecord 模型中的属性创建默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过在 ActiveRecord 中定义属性来为其创建默认值.默认情况下,每次创建记录时,我都希望属性 :status 有一个默认值.我试图这样做:

I want to create a default value for an attribute by defining it in ActiveRecord. By default everytime the record is created, I want to have a default value for attribute :status. I tried to do this:

class Task < ActiveRecord::Base
  def status=(status)
    status = 'P'
    write_attribute(:status, status)
  end
end

但是在创建时我仍然从数据库中检索到这个错误:

But upon creation I still retrieve this error from the database:

ActiveRecord::StatementInvalid: Mysql::Error: Column 'status' cannot be null

因此,我认为该值未应用于该属性.

Therefore I presume the value was not applied to the attribute.

在 Rails 中执行此操作的优雅方式是什么?

What would be the elegant way to do this in Rails?

非常感谢.

推荐答案

可以为迁移中的列设置默认选项

You can set a default option for the column in the migration

....
add_column :status, :string, :default => "P"
....

你可以使用回调,before_save

class Task < ActiveRecord::Base
  before_save :default_values
  def default_values
    self.status ||= 'P' # note self.status = 'P' if self.status.nil? might be safer (per @frontendbeauty)
  end
end

这篇关于Rails:如何为 Rails activerecord 模型中的属性创建默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆