gpt4 book ai didi

ruby-on-rails - 如何在Rails中序列化嵌套模型?

转载 作者:行者123 更新时间:2023-12-04 01:58:38 26 4
gpt4 key购买 nike

我要弄清楚如何在Rails中序列化模型的嵌套属性非常困难。我有一个RecipeTemplate,它将在它的template_data属性中存储一个已经存在的配方。配方具有两个层次的嵌套属性。

这是在 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

“配方”中的“成分”也具有嵌套属性(“子成分”)。

如果我用这样的对象设置template_data:
Recipe.includes(:ingredients => [:sub_ingredients]).find(1)

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

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

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

预先感谢您的任何帮助

最佳答案

我可以看到为什么您希望模板本身存储在序列化列中,但是与该类型的列所允许的相比,您需要对存储的数据进行更多的操作。这是我会做的:

app/models/recipe_template.rb

class RecipeTemplate < ActiveRecord::Base
serialize :template_data

attr_accessible :name, :recipe

def recipe=(r)
self.template_data = r.serializable_hash_for_template
end

def recipe
Recipe.new(template_data)
end
end

app/models/recipe.rb
class Recipe < ActiveRecord::Base
has_many :ingredients, as: :parent
accepts_nested_attributes_for :ingredients

attr_accessible :name, :ingredients_attributes

def serializable_hash_for_template(options={})
options[:except] ||= [:id, :created_at, :updated_at]
serializable_hash(options).tap do |h|
h[:ingredients_attributes] = ingredients.map(&:serializable_hash_for_template)
end
end
end

app/models/ingredient.rb
class Ingredient < ActiveRecord::Base
belongs_to :parent, polymorphic: true
has_many :sub_ingredients, class_name: 'Ingredient', as: :parent
accepts_nested_attributes_for :sub_ingredients

attr_accessible :name, :sub_ingredients_attributes

def serializable_hash_for_template(options={})
options[:except] ||= [:id, :parent_id, :parent_type, :created_at, :updated_at]
serializable_hash(options).tap do |h|
h[:sub_ingredients_attributes] = sub_ingredients.map(&:serializable_hash_for_template)
end
end
end

然后创建并使用模板:
# create a recipe to use as a template
taco_meat = Ingredient.create(name: "Taco Meat")
taco_seasoning = taco_meat.sub_ingredients.create(name: "Taco Seasoning")
sams_tacos = Recipe.create(name: "Sam's Tacos")
sams_tacos.ingredients << taco_meat

# create a template from the recipe
taco_recipe = RecipeTemplate.create(name: "Taco Recipe", recipe: sams_tacos)

# build a new recipe from the template
another_taco_recipe = taco_recipe.recipe

不同之处在于您使用序列化列存储要在配方构造器中使用的哈希。如果您只想序列化该对象,则其他张贴者都是正确的-只需关联一个对象即可。

关于ruby-on-rails - 如何在Rails中序列化嵌套模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6719898/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com