How to create dynamic attribute aliases in rails?

2019-09-02 04:47发布

问题:

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!