首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >我怎样才能在ActiveRecord中设置默认值?

我怎样才能在ActiveRecord中设置默认值?

提问于 2017-12-20 13:13:34
回答 2关注 0查看 270

如何在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, :defaults
end
I have seen the following examples googling around:
  def initialize 
    supe
    self.status = ACTIVE unless self.status
  end
and
  def after_initialize 
    return unless new_record?
    self.status = ACTIVE
  end

代码中把它放在迁移中,但是我想看到模型代码中定义。

有没有规范的方式来设置ActiveRecord模型中的字段的默认值?

回答

和开发者交流更多问题细节吧,去 写回答
相关文章

相似问题

相关问答用户
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档