我的模型用户上有一列称为属性,即jsonb。因为我需要用户生成动态字段。
如何像对待普通映射列一样访问属性
例如 用户模型有一个名为first_name的列,但属性中的一个属性为eye_color
user = User.find(1)
user.first_name # => "john"
# to access the eye color you would do
user.properties['eye_color'] # => "green"
我想做的是能够调用map json属性,这样我就可以像下面这样设置和获取它
user.eye_color = 'green'
这需要动态完成,因为字段属性可以更改。但是,在用户实例上,我可以看到计算出所有属性的含义。
答案 0 :(得分:1)
也许可以在您的method_missing
模型上覆盖User
def method_missing(method, *args, &block)
clean_method = method.to_s.chomp('=')
if properties.key?(clean_method)
if method.to_s.ends_with?('=')
return properties[clean_method] = args.first
else
return properties[clean_method]
end
end
super
end
这应该允许您直接获取和设置
# set value
user.eye_color = 'green'
# get value
user.eye_color # => returns 'green'