如何在Rails中序列化嵌套模型?

Mun*_*PhD 6 serialization activerecord ruby-on-rails nested-attributes

我很难搞清楚如何在rails中序列化模型的嵌套属性.我有一个RecipeTemplate,它将已存在的Recipe存储在它的template_data属性中.Recipe有两个级别的嵌套属性.

这是在rails 3.1.0.rc4上

class RecipeTemplate < ActiveRecord::Base
  serialize :template_data, Recipe
 ...
end

class Recipe < ActiveRecord::Base
  has_many :ingredients
  accepts_nested_attributes_for :ingredients
 ...
end
Run Code Online (Sandbox Code Playgroud)

Recipe中的成分也有嵌套属性(SubIngredients).

如果我使用如下对象设置template_data:

Recipe.includes(:ingredients => [:sub_ingredients]).find(1)
Run Code Online (Sandbox Code Playgroud)

我会得到一个TypeError"无法转储匿名类Class",这是有道理的,因为它不知道如何序列化Ingredients或SubIngredients.

如何序列化模型中的嵌套属性,以便您可以使用:

 serialize :template_data, Recipe
Run Code Online (Sandbox Code Playgroud)

或者我是否必须以其他方式序列化数据并自行执行类型安全检查?

在此先感谢您的帮助

Ban*_*eil -2

为什么不在 RecipeTemplate 模型中保留一个带有标签的字段recipe_id

并将其链接到配方而不是尝试序列化配方对象?