Rails ActiveRecord 存储中的动态属性

dynamic attributes in Rails ActiveRecord store

我有一个子模型,它应该能够通过 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?我猜我需要某种元编程吗?!

如果我理解正确,基本上您需要在子对象实例化时为父对象 content_attributes 执行数据库查找,然后根据该数据动态分配访问器。

按照这些思路可能会奏效 - How do I set an attr_accessor for a dynamic instance variable?

您可以尝试执行查找的 after_initialize 回调,然后在单例 class.

上调用 store_accessor

这是我的解决方案:

  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