【发布时间】:2018-04-13 21:41:36
【问题描述】:
在我的控制器中,我定义了一个方法,我想在没有表单的情况下自动保存到我的数据库中。
这是我目前所拥有的,但没有任何内容保存到数据库中。
方法如下
def recommended_recipes
@today = Date.today
@recRecipe = RecommendedRecipe.where(user_id: current_user, day: @today)
if @recRecipe.blank?
response = RestClient.get("https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/mealplans/generate?targetCalories=3000&timeFrame=day", headers={"X-Mashape-Key" => "",
"Accept" => "application/json"})
@parsedResponse = JSON.parse(response)
@recRecipes = @parsedResponse['meals']
@recRecipesNutrients = @parsedResponse['nutrients']
@totalCalories = @recRecipesNutrients['calories']
@totalProteins = @recRecipesNutrients['protein']
@totalFat = @recRecipesNutrients['fat']
@totalCarbohydrates = @recRecipesNutrients['carbohydrates']
@newRecRecipe = RecommendedRecipe.create(meals_response: @recRecipes, total_calories: @totalCalories, total_proteins: @totalProteins, total_fat: @totalFat, total_carbohydrates: @totalCarbohydrates, day: @today, user_id: current_user)
end
end
每当调用该方法时,我想将 @newRecipe 保存到名为 recommended_recipes 的数据库中。 如何在数据库中记录?
提前致谢!
【问题讨论】:
-
问题是什么?
-
我怎样才能实现我的目标。目前它没有保存任何东西。我会更新我的问题。
-
首先将
RecommendedRecipe.create更改为RecommendedRecipe.create!。如果没有抛出错误,那么@recRecipe.blank?的评估结果可能是false。您可以尝试将if @recRecipe.blank?更改为unless @recRecipe.any?。如果抛出错误,那么您的验证很可能有问题。
标签: ruby-on-rails database postgresql object record