如何创建延迟的复杂对象创建

时间:2016-10-31 13:34:31

标签: ruby-on-rails ruby

我遇到了这个问题: 我有一个复杂的模型,食谱,其中有__成分,属于用户,有回形针图像。

我尝试为每个新用户创建一些基础对象。例如:配方,配有它的成分(每个用户都是不同的)。 如何创建一个工作来处理这些食谱创作?知道他们必须可以被他们的用户等编辑。对于没有关系的基本模型来说很容易但是我在这里被阻止了......

- 我不想为所有用户创建配料或食谱,我希望他们能够删除它们。

以下是随机用户创建单个食谱的参数:

Parameters: {"utf8"=>"✓", "recipe"=>{"name"=>"Recipe test", "category"=>"Chocolate", "owner"=>"Tom", "baking"=>"100", "note"=>"",
"quantities_attributes"=>{"0"=>{"ingredient_id"=>"6434", "weight"=>"100", "_destroy"=>"false"}, "1"=>{"ingredient_id"=>"6681", "weight"=>"10", "_destroy"=>"false"}, "2"=>{"ingredient_id"=>"6668", "weight"=>"210", "_destroy"=>"false"}, "3"=>{"ingredient_id"=>"6591", "weight"=>"100", "_destroy"=>"false"}, "4"=>{"ingredient_id"=>"6611", "weight"=>"20", "_destroy"=>"false"}, "5"=>{"ingredient_id"=>"", "weight"=>"", "_destroy"=>"false"}},
"process"=>"<p>This is a f*** test of recipe recipe creation</p>\r\n\r\n<p><img alt=\"\" height=\"26\" src=\"http://localhost:3000/assets/ckeditor/plugins/smiley/images/Emoji Smiley-109.png\" title=\"\" width=\"26\" /></p>\r\n"}, 
"commit"=>"SUBMIT"}

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

您可以将食谱和配料作为主表,您可以创建另一个模型,如UserRecipeIngredients,它将充当用户,配方和配料之间的连接表。此联接表将包含user_idrecipe_id以及ingredient_id,此模型将具有如下所示的关联。

belongs_to user
belongs_to recipe
belongs_to ingrdient

答案 1 :(得分:1)

很抱歉,如果我的问题不清楚,我通过定义一个成分变量找到了解决方案:

ingredient = user.ingredients.find_by_name("Apricots")
user.recipes.create!([
            { name: "test", category: "Chocolats", baking: "110", quantities_attributes: {"0"=>{"ingredient_id"=>ingredient.id, "weight"=>"100", "_destroy"=>"false"}},process: "try &nbsp;<img alt=\"\" height=\"26\"src=\"http://localhost:3000/assets/ckeditor/plugins/smiley/images/Emoji Smiley-109.png\""}
            ])

感谢您的帮助@Jayaprakash&amp; @Thounder

答案 2 :(得分:0)

我不确定是否正确理解您的问题,但是您不应该在数据库中存储虚假数据。

如果是出于某种目的显示,请在食谱模型中定义一个方法,该方法使用假的许多成分构建假记录,并在

中的任何位置调用它

另一方面,如果您希望在创建用户记录后执行操作,例如,只需在用户模型上定义after_create回调