如何创建在Rails的ActiveRecord的模型属性的默认值? [英] How do I create a default value for attributes in Rails activerecord's model?
本文介绍了如何创建在Rails的ActiveRecord的模型属性的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过定义它的ActiveRecord创造一个属性的默认值。默认情况下,每次创建记录,我想有属性默认值:状态
。我试图做到这一点:
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
所以我presume的价值没有被应用到属性。
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
或
您可以使用一个回调,before_save
You can use a callback, before_save
class Task < ActiveRecord::Base
before_save :default_values
def default_values
self.status ||= 'P'
end
end
这篇关于如何创建在Rails的ActiveRecord的模型属性的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文