You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby on Rails 5:无需表单自动写入数据库的方法未生效问题

Let's walk through the most likely reasons your automatic database save isn't working, based on the code snippet you shared:

1. You're Missing the Creation/Save Logic

The biggest red flag here is that your current code only checks if a RecommendedRecipe exists for the user today, and calls the Spoonacular API—but you never actually create and save a new RecommendedRecipe record with the API data.

Here's how to fix that:

def recommended_recipes
  @today = Date.today
  # Use .exists? for a more efficient check than .blank?
  unless RecommendedRecipe.exists?(user_id: current_user.id, day: @today)
    begin
      response = RestClient.get(
        "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/mealplans/generate?targetCalories=3000&timeFrame=day",
        headers: {"X-Mashape-Key": YOUR_API_KEY_HERE} # Fill in your actual key
      )
      # Parse the API's JSON response
      recipe_data = JSON.parse(response.body)
      
      # Create and save the record
      RecommendedRecipe.create!(
        user_id: current_user.id,
        day: @today,
        # Map API data to your model's fields (adjust based on your schema)
        meal_plan: recipe_data["meals"],
        daily_calories: recipe_data["nutrients"]["calories"]
      )
    rescue RestClient::ExceptionWithResponse => e
      # Handle API errors (log them for debugging)
      Rails.logger.error "Spoonacular API Error: #{e.response.body}"
    end
  end
end

Using create! instead of create will raise an exception if the save fails, which makes debugging way easier than silent failures.

2. Model Validation Failures

Even if you add save logic, your RecommendedRecipe model might have validations that are failing (like required fields missing or invalid data types).

To debug this, replace create! with a manual save and check the error messages:

rec_recipe = RecommendedRecipe.new(
  user_id: current_user.id,
  day: @today,
  # ... other fields
)

if rec_recipe.save
  # Success
else
  # Print errors to your server log or console
  Rails.logger.error "Save failed: #{rec_recipe.errors.full_messages.join(', ')}"
end

3. current_user Might Be nil

If the user isn't logged in when this method runs, current_user will be nil. This breaks both your initial query and the save (since user_id would be nil, which likely violates a validation in your model).

Add a guard clause to ensure the user is authenticated first:

def recommended_recipes
  return unless current_user.present? # Exit early if no user is logged in
  # Rest of your logic...
end

4. API Response Parsing Issues

Double-check that you're correctly parsing the API response. If the JSON structure doesn't match what you're expecting (e.g., missing meals or nutrients keys), you'll end up trying to save nil values, which might trigger validation errors.

Add a log to inspect the raw response:

Rails.logger.debug "Spoonacular API Response: #{response.body}"

内容的提问来源于stack exchange,提问作者Alexander Bogdanov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:39:32