如何在ActiveRecord中设置默认值?
class Item < ActiveRecord::Base def initialize_with_defaults(attrs = nil, &block) initialize_without_defaults(attrs) do setter = lambda { |key, value| self.send("#{key.to_s}=", value) unless !attrs.nil? && attrs.keys.map(&:to_s).include?(key.to_s) } setter.call('scheduler_type', 'hotseat') yield self if block_given? end end alias_method_chain :initialize, :defaultsendI have seen the following examples googling around: def initialize supe self.status = ACTIVE unless self.status endand def after_initialize return unless new_record? self.status = ACTIVE end代码中把它放在迁移中,但是我想看到模型代码中定义。
有没有规范的方式来设置ActiveRecord模型中的字段的默认值?
相似问题