首页 > 解决方案 > Ruby on Rails:表单成功提交但没有提交到数据库并且没有显示错误

问题描述

我是一个 RoR 新手,我目前正在制作一个杂货清单应用程序。当我尝试提交表单时,它会返回到同一页面,并且没有显示我成功制作了购物清单。我检查了我的数据库,没有提交的数据。同时,在控制台或浏览器中都没有错误提示。这是我的控制器、表单以及用户和grocery_list 之间的关联。

 class GroceryListsController < ApplicationController

 def new
     @grocery_list = GroceryList.new
 end

 def create
     @grocery_list = current_user.grocery_lists.build(grocery_list_params)
  if @grocery_list.save
     redirect_to grocery_lists_path, notice: "Created successfully"
  else
     render :new
   end
 end

 private
    def grocery_list_params
      params.require(:grocery_list).permit(:name, :date)
    end
 end

这是我的表格

<h1>Make your grocery list</h1>

<%= form_for GroceryList.new do |f| %>
  <%= f.text_field :name, placeholder:'Name of your grocery list' %>
  <%= f.date_field :date %>
  <%= f.submit 'Create list' %>
<% end %>

用户模型

class User < ApplicationRecord

   devise :database_authenticatable, :registerable,
          :recoverable, :rememberable, :validatable

   has_many :grocery_lists
end

和grocery_list 模型

class GroceryList < ApplicationRecord
   belongs_to :user
   belongs_to :product
end

标签: ruby-on-rails

解决方案


这里的主要问题是您的模型中有belongs_to :product关联。GroceryList

class GroceryList < ApplicationRecord
   belongs_to :user
   belongs_to :product
end

由于 Rails 5belongs_to关联默认情况下是非可选的。这意味着关联会validates_presence_of :product自动添加关联。

它也很可能不是您想要的,因为它只会让您将单个产品添加到购物清单中。相反,您想要一个has_many through:关联

class GroceryList < ApplicationRecord
   belongs_to :user
   has_many :grocery_list_items
   has_many :products, through: :grocery_list_items
end

# rails g model GroceryListItem grocery_list:belongs_to product:belongs_to quantity:decimal
class GroceryListItem < ApplicationRecord
   belongs_to :grocery_list
   belongs_to :product
end 

class Product < ApplicationRecord
   has_many :grocery_list_items
   has_many :grocery_lists, through: :grocery_list_items
end 

您还应该传递@grocery_listform_for而不是创建一个新实例,该实例将清除任何用户输入并向用户显示验证错误:

<%= form_for @grocery_list do |f| %>
  <% if @grocery_list .errors.any? %>
  <div class="errors">
    <h2><%= pluralize(@grocery_list.errors.count, "error") %> prohibited this grocery list from being saved:</h2>
    <ul>
      <% @grocery_list.errors.each do |error| %>
        <li><%= error.full_message %></li>
      <% end %>
    </ul>
  </div>
  <% end %>
  <%= f.text_field :name, placeholder:'Name of your grocery list' %>
  <%= f.date_field :date %>
  <%= f.submit 'Create list' %>
<% end %>

推荐阅读