我在我的模型中添加了这样的HSTORE类型:
serialize :settings, ActiveRecord::Coders::Hstore
然后我在我的模型中添加了以下内容以获取键值而无需使用方括号。
# Add the possibility to inquire HSTORE keys values without brackets
# ex. @company_settings.settings['locale'] => @company_settings.locale
def method_missing(id, *args, &block)
if settings.has_key?(id.to_s)
settings.fetch(id.to_s)
else
super
end
end
对于平等运营商,有没有办法做同样的事情?即。
@ company_setting.locale ='en'
修改
如果我执行'@ company_setting.locale
,这是我得到的错误NoMethodError: undefined method `locale=' for #<CompanySettings:0x42e9a78>
from D:/Software/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activemodel-3.2.1/lib/active_model/attribute_methods.rb:407:in `method_missing'
from D:/Software/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activerecord-3.2.1/lib/active_record/attribute_methods.rb:126:in `method_missing'
from D:/ASM/source/app/app/models/company_settings.rb:23:in `method_missing'