我有一个模型在数据库中有一个实际列。该列存储为配置的JSON字符串。我使用了一堆虚拟属性,我想在这个配置JSON属性中映射这些属性。我基本上不想在数据库中创建一堆列,而是使用这一个JSON属性来包含所有内容。有没有比实现这个的def
更简洁的方法?使虚拟属性成为一个哈希的一部分
class Device < ActiveRecord::Base
attr_accessible :configuration
serialize :configuration, JSON
attr_accessor :background_color, :title
# below is ew
def background_color; self.configuration["background_color"]; end
def background_color=(value); self.configuration["background_color"] = value; end
def title; self.configuration["title"]; end
def title=(value); self.configuration["title"] = value; end
end
理想情况下,我会寻找像attr_maps_to_hash :configuration, [:background_color, :title]
。有这样的事情存在吗?
我想到的另一个解决方法是在属性符号数组上使用'class_eval'来生成getters和setters,但这也很丑陋。 – Larry 2013-03-21 21:43:36