考虑下面的ActiveRecord模型与enum
柱:如何为活动记录枚举指定默认值?
class User < ActiveRecord::Base
enum role: [:normal, :sales, :admin]
end
如何设置为role
列之前保存到数据库的默认值。
例如:
user = User.new
puts user.role # Should print 'normal'
考虑下面的ActiveRecord模型与enum
柱:如何为活动记录枚举指定默认值?
class User < ActiveRecord::Base
enum role: [:normal, :sales, :admin]
end
如何设置为role
列之前保存到数据库的默认值。
例如:
user = User.new
puts user.role # Should print 'normal'
class User < ActiveRecord::Base
enum role: [:normal, :sales, :admin]
after_initialize do
if self.new_record?
self.role ||= :normal
end
end
end
或者如果你喜欢
class User < ActiveRecord::Base
enum role: [:normal, :sales, :admin]
after_initialize :set_defaults
private
def set_defaults
if self.new_record?
self.role ||= :normal
end
end
end
注意,我们使用|| =来防止after_initialize破坏任何传递的内容在使用User.new进行初始化期间(some_params)
当用角色初始化对象时会发生什么:'User.new(role:'sales')'? –
该死的你是对的。 after_initialize会跺脚参数...所以我需要一个|| =不会覆盖它。更新我的答案。 –
您可以使用此回调,before_save
class User < ActiveRecord::Base
before_save :default_values
def default_values
self.role ||= "normal"
end
end
用你的代码'user = User.new; user.role'将返回'nil'。 –
为什么不尝试通过迁移将现有列添加默认值。 – BENS
保存模型后,数据库中设置的默认值仅适用于**。 –
您可以在迁移文件中将其设置为:默认为'normal'。
一点很好的例子:LINK
class User < ActiveRecord::Base
enum role: [:normal, :sales, :admin]
#before_save {self.role ||= 'normal'}
# or
#before_create {self.role = 'normal'}
end
是否有你需要保存到数据库之前做了具体的原因是什么?这可以在将记录保存到db期间完成吗? – uday