ruby-on-rails - Rails ActiveRecord 存储中的动态属性

标签 ruby-on-rails ruby activerecord metaprogramming accessor

我有一个子模型,它应该能够通过 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/

相关文章:

ruby-on-rails - ruby on rails 关系不起作用

ruby - 无法破译包含映射运算符的 Ruby 行

mysql - rails 引擎 : Namespacing foreign key references to other models in the same engine

mysql - 为什么使用 ActiveRecord 而不是 MySql API

ruby-on-rails - 更新事件存储附件文件名

ruby-on-rails - 如何创建这条路线?

ruby-on-rails - 为嵌套资源创建新的 link_to

ruby-on-rails-3 - Rails 3 Active Record 动态 find_or_create finder 方法是否存在一些未记录的不一致?

ruby-on-rails - Rails 3 中的 find_or_create_by 和更新以创建记录

ruby-on-rails - 如何验证 Rails 模型中的 url?