简体   繁体   中英

Create a record to the database without a form in Ruby on Rails 5

In my controller I have defined a method that I want to save to my database automatically without a form.

This is what I have so far, but nothing is being saved to the database.

Here's the method

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

I want to save the @newRecipe to my database called recommended_recipes whenever the method is called. How can I make a record in the database?

Thanks in advance!

After hours of kicking myself in the head I did this in the model:

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

I added the optional: true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM