【问题标题】:Create a record to the database without a form in Ruby on Rails 5在 Ruby on Rails 5 中创建没有表单的数据库记录
【发布时间】: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


【解决方案1】:

几个小时后,我在模型中做了这个:

class RecommendedRecipe < ApplicationRecord
    belongs_to :user, optional: true
end

我添加了 optional: true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    相关资源
    最近更新 更多