ruby-on-rails - 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
解决方案
这里的主要问题是您的模型中有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_list
给form_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 %>
推荐阅读
- mysql - 如何在单独的表中显示对应于 ID where user = x WHEN 的所有 MYSQL 表值
- typescript - 在打字稿函数返回值中保留类型信息
- python - 将 Audioset ckpt 转换为 pb 文件
- c# - 获取数据库C#中的表总数
- javascript - 尝试在Javascript中比较不同数组中的对象
- java - 可执行 .jar 未运行 JavaFX - Ecliipse
- vb.net - 使用 IEnumerable 返回字符串的所有可能性
- java - turnRight 方法在组合锁程序中不起作用 - java
- c# - 从控制台应用程序创建/更新数据库模式
- javascript - jQuery.html() 函数不保留动态 DOM 中的选择和输入中的值