Rails 个没有更多模型的嵌套变量

Rails nested variables without more models

我正在使用 Rails 4 并且有一个 Policy 模型。这个模型有很多属性,我想将它们组织成各种子组。这是一个例子:

一个策略有名称、地址、类型等基本信息。有没有办法组织模型,这样我就可以做 policy.base_information.namepolicy.base_information.address 而无需制作另一个模型 base_information?

谢谢!

您可以使用 serialize with OpenStruct 来完成任务。

序列化

If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object, then specify the name of that attribute using this method and it will be handled automatically.

OpenStruct

An OpenStruct is a data structure, similar to a Hash, that allows the definition of arbitrary attributes with their accompanying values. This is accomplished by using Ruby’s metaprogramming to define methods on the class itself.


:base_information 上调用 serialize 方法,这是一个 OpenStruct:

class Policy < ActiveRecord::Base
  serialize :base_information, OpenStruct
end

所以,现在可以进行以下操作:

policy = Policy.create(:base_information => { "name" => "vasseurth" })

Policy.find(policy.id).base_information 
# => { "name" => "vasseurth" }

Policy.find(policy.id).base_information.name
# => "vasseurth"