Ber*_*n_J 1 ruby activerecord metaprogramming ruby-on-rails accessor
我有一个子模型,它应该能够通过 ActiveRecord::Store 功能存储不同的属性。这些属性应由父模型确定。为此,父模型有一列将content_attributes子模型的属性存储为字符串数组(即['color', 'size', 'age'])。
为了在子实例中拥有父级定义的所有属性的访问器,我当前使用一种解决方法来映射所有可用父级的所有属性名称:
class child
belongs_to :parent
store :content, accessors: Parent.all_content_attributes, coder: JSON
...
end
Run Code Online (Sandbox Code Playgroud)
实际上,我只想为不同父级的所有属性设置访问器。然而,在上面的示例中,子实例将获得一长串可有可无的属性名称。如何更换Parent.all_content_attributes?我猜我需要某种元编程?!
这是我的解决方案:
store :content_store, coder: JSON
after_initialize :add_accessors_for_content_attributes
def add_accessors_for_content_attributes
content_attributes.each do |attr_name|
singleton_class.class_eval do
store_accessor :content_store, attr_name
end
end
end
def content_attributes
parent.content_attributes.map(&:name)
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1669 次 |
| 最近记录: |