加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 具有默认值的ActiveRecord :: Store

发布时间:2020-12-16 21:35:17 所属栏目:百科 来源:网络整理
导读:使用新的ActiveRecord :: Store进行序列化,the docs给出了以下示例实现: class User ActiveRecord::Base store :settings,accessors: [ :color,:homepage ]end 可以使用默认值声明属性,类似于: store :settings,accessors: { color: 'blue',homepage: 'rub
使用新的ActiveRecord :: Store进行序列化,the docs给出了以下示例实现:
class User < ActiveRecord::Base
  store :settings,accessors: [ :color,:homepage ]
end

可以使用默认值声明属性,类似于:

store :settings,accessors: { color: 'blue',homepage: 'rubyonrails.org' }

解决方法

不,没有办法在商店通话中提供默认值. store macro很简单:
def store(store_attribute,options = {})
  serialize store_attribute,Hash
  store_accessor(store_attribute,options[:accessors]) if options.has_key? :accessors
end

所有的store_accessor都是通过访问器来遍历,并为每个访问器创建访问器和mutator方法.如果您尝试使用Hash with:访问器,您最终会向您的商店添加一些您不想要的东西.

如果要提供默认值,则可以使用after_initialize钩子:

class User < ActiveRecord::Base
  store :settings,:homepage ]
  after_initialize :initialize_defaults,:if => :new_record?
private
  def initialize_defaults
    self.color    = 'blue'            unless(color_changed?)
    self.homepage = 'rubyonrails.org' unless(homepage_changed?)
  end
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读