2017-08-22 81 views
0

我有一個子模型,它應該能夠通過ActiveRecord :: Store功能存儲不同的屬性。這些屬性應該由父模型確定。爲此,父模型具有列content_attributes,其將兒童屬性存儲爲字符串數組(即['color', 'size', 'age'])。Rails ActiveRecord商店中的動態屬性

要在由父定義的所有屬性的子實例存取,我目前使用它映射所有屬性的所有可用父母的姓名解決方法:

class child 
    belongs_to :parent 

    store :content, accessors: Parent.all_content_attributes, coder: JSON 
    ... 
end 

其實,我只是想設置訪問對獨特父代的所有屬性。然而,在上面的例子中,子實例會得到一個很長的可有可無的屬性名稱列表。如何更換Parent.all_content_attributes?猜猜我需要某種元編程嗎?!

回答

1

這裏是我的解決方案:

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 
1

如果我理解正確,實際上您需要在實例化子對象時爲父content_attributes執行數據庫查找,然後根據該數據動態分配訪問器。

東西沿着這些線路可以工作 - How do I set an attr_accessor for a dynamic instance variable?

你可以嘗試的after_initialize回調,做了查找,然後調用store_accessor的單例類。

+0

是不是一個問題,那我有期間或初始化之前定義存取,因爲我已經需要初始化,即Child.new(顏色在那些:. ..)?但無論如何,我會試一試! –