How to create dynamic attribute aliases in rails?

寵の児 提交于 2019-12-13 04:42:10

问题


In class definition I got a list of attributes that I want to return other than database's values unless the container for store of those values is nil:

class Label < ActiveRecord::Base

   CONFIRM_DATA = ["attr1", "attr2"]
   # "attr1", "attr2" is database fields

   CONFIRM_DATA.each do |att|
      alias_attribute "original_#{att}".to_sym, att.to_sym
      define_method att.to_sym do
         temp_attr_store[ att.to_sym ] || read_attribute( "original_#{att}".to_sym)
      end
   end
end

So as you see, I try to store in temp_attr_store some temp values for the attributes: they should appear instead of db values and hopefully affect the associations for the object.

The code above does not work, all attr1 access results in nil. Thank you!

来源:https://stackoverflow.com/questions/26092815/how-to-create-dynamic-attribute-aliases-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!