我有一个子模型,它应该能够通过 ActiveRecord::Store 特性存储不同的属性。这些属性应由父模型确定。为此,父模型有一列 content_attributes
,它将子属性存储为字符串数组(即 ['color', 'size', 'age']
) .
要在子实例中访问父实例定义的所有属性,我目前使用一种变通方法,它映射所有可用父实例的所有属性名称:
class child
belongs_to :parent
store :content, accessors: Parent.all_content_attributes, coder: JSON
...
end
实际上,我只想为不同父级的所有属性设置访问器。但是,在上面的示例中,子实例将获得一长串可有可无的属性名称。如何替换 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
关于ruby-on-rails - Rails ActiveRecord 存储中的动态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45823311/