如何在模型中设置默认值?-- 在 Ruby on Rails 3.1 中 [英] How to set default values in models? -- in Ruby on Rails 3.1
问题描述
在 RoR 3.1 中,验证"仍然无法在模型中设置默认值.或者有吗?如果没有,设置默认值的最佳方法是什么?
In RoR 3.1, "validates" still doesn't have a way of setting default values in the models. Or is there? If not, what's the best way to set default values?
推荐答案
一种方法是在迁移中设置默认值.这将是一个将设置为您的数据库的属性.您可以在此处阅读更多信息:http://api.rubyonrails.org/classes/ActiveRecord/Migration.html
One approach would be to set the default in your migration. This will be a property that will get set to your database. You can read more here: http://api.rubyonrails.org/classes/ActiveRecord/Migration.html
另一种方法是设置一个before过滤器,例如before_save或before_create,然后检查属性上的值是否为nil,您可以将其设置为某物.
The other approach is to set a before filter, something like before_save or before_create, and then check if the value on an attribute is nil, you can set it to something.
class Abc
before_save :set_default
protected
def set_default
self.xyz = "default" unless self.xyz
end
end
这篇关于如何在模型中设置默认值?-- 在 Ruby on Rails 3.1 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!