Ruby 在 Rails 添加新数据失败

Ruby on Rails failed to add a new data

我正在做简单的增删改查,目前的目标是添加数据。但是,我发现我无法添加任何数据,终端日志也显示“[Webpacker] Everything's up-to-date. Nothing to do”,也就是说没有报错信息。

按照我在controller中的设计,新数据肯定是失败了,所以停在了new.html.erb。估计跟模特关系有关系

这是模型用户

class User < ApplicationRecord
  has_many :reviews
  has_many :recipes, through: :reviews
end

这是模型食谱

class Recipe < ApplicationRecord
  has_many :reviews
  belongs_to :user
end

这是模型评论

class Review < ApplicationRecord
  belongs_to :user
  belongs_to :recipe
end

这是 RecipeController

class RecipesController < ApplicationController

  def index
    @recipes = Recipe.all  
  end

  def new
    @recipe = Recipe.new  
  end

  def create
    @recipe = Recipe.new(recipe_params)
    
    if @recipe.save
      redirect_to recipes_path, notice: "Successful!"
    else
      render :new
    end
  end

private

  def recipe_params
    params.require(:recipe).permit(:title, :money)
  end
end

这是网页

<h1>Add New One</h1>

<%= form_for(@recipe) do |r| %>
  <%= r.label :title, "Title" %>
  <%= r.text_field :title%>

  <%= r.label :money, "Budget" %>
  <%= r.text_field :money %>

  <%= r.submit %>
<% end %>

<%= link_to "Back to list", recipes_path %>

您可能是对的,这是与 belongs_to 关系相关的验证错误。您应该按照此处所述 https://guides.rubyonrails.org/getting_started.html#validations-and-displaying-error-messages

显示表单的验证错误

您应该首先添加一个回调以确保只有登录用户才能创建食谱(除非您真的想让匿名用户 create/update/delete 食谱)。

例如,对于 Devise,您可以使用它的 authenticate_user! 助手,如果用户未通过身份验证,它将退出并重定向到登录路径:

class RecipesController < ApplicationController
  before_action :authenticate_user!, only: [:new, :create]

  # ...
end

如果您正在重新发明身份验证轮,您应该创建一个类似的方法来防止访问。

然后您将初始化当前用户的资源:

class RecipesController < ApplicationController
  before_action :authenticate_user!, except: [:show, :index]

  def create
    @recipe = current_user.recipes.new(recipe_params)
    if @recipe.save
      redirect_to recipes_path, notice: "Successful!"
    else
      render :new
    end
  end
end

这里我假设您有一个 current_user 方法,该方法将根据存储会话的 ID 检索用户。

由于您有间接关联,这将在 reviews table 中创建一行,用户 ID 和食谱 ID 作为食谱 table 中的记录。

您还希望在表单中display the validation errors以便用户获得反馈。