2016-10-31 48 views
1

我得到这个问题: 我有一个复杂的模型,食谱,has_many成分,belongs_to用户,有回形针的图像。如何创建延迟的复杂对象创建

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

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

这里有一个单一的配方创造PARAMS通过随机用户:

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"} 

任何想法?

回答

1

您可以将食谱和配料作为主表,您可以创建另一个模型,如UserRecipeIngredients,它将充当用户,食谱和配料之间的连接表。这个连接表应该有user_idrecipe_idingredient_id,这个模型会有如下的关联。

belongs_to user 
belongs_to recipe 
belongs_to ingrdient 
+0

我做了一个数量表(“quantity_attributes”=>等),但这不是我的问题..我的问题是为这些模型为每个用户创建一个随机配方。例如:@ user.recipe.create(name:“”等。quantities_attributes:{PROBLEM HERE})如何处理没有配料ID的数量 –

0

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

如果是为了某种目的而显示,定义在配方模型的方法,其建立与假许多成分假的记录,并调用它,无论你在

在另一方面想,如果你想要一个动作要做的是创建一个用户记录之后,例如,只是定义您的用户模型中的after_create回调

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 & @Thouter