ruby-on-rails - Rails:无效记录创建后的错误不显示
问题描述
我正在尝试创建一个简单的应用程序,它允许登录用户(属于组 - 组表)创建组事务。但是,在我提交无效表单后我没有收到任何错误(我有验证) .
这是我的控制器:
class GroupTransactionsController < ApplicationController
before_action :get_group, only: [:new, :create, :destroy, :index, :show]
before_action :how_many_members, only: [:new, :show, :create]
before_action :set_transaction_number, only: [:index]
def new
@group_transaction = @group.group_transactions.new
@members.times { @group_transaction.group_transaction_borrowers.build }
end
def create
@group_transaction = @group.group_transactions.build(group_transactions_params)
if @group_transaction.save
flash[:success] = "Group transactions has been made"
redirect_to group_group_transactions_path(@group)
else
render 'new'
end
end
private
def group_transactions_params
params.require(:group_transaction).permit(:issuer_id, :value, :description,
group_transaction_borrowers_attributes:
GroupTransactionBorrower.attribute_names.map(&:to_sym))
#output of the line above: [:id, :created_at, :updated_at, :group_transactions_id,
:borrower_id]
end
def get_group
@group = Group.find(params[:group_id])
end
def how_many_members
@members = Group.find(params[:group_id]).relations.count
end
end
这是 GroupTransaction 模型:
class GroupTransaction < ApplicationRecord
has_many :group_transaction_borrowers, dependent: :destroy
belongs_to :issuer, class_name: "User", foreign_key: "issuer_id"
belongs_to :group
accepts_nested_attributes_for :group_transaction_borrowers, reject_if: :ignore_empty
#basic validations
validates :value, presence: true, numericality: { greater_than: 0 }
validates :description, presence: true, length: { maximum: 20 }
validates_associated :group_transaction_borrowers
validates_presence_of :group_transaction_borrowers
def ignore_empty(attributes)
attributes['borrower_id'].blank?
end
end
这是 GroupTransactionBorrower 模型:
class GroupTransactionBorrower < ApplicationRecord
belongs_to :group_transaction
belongs_to :borrower, class_name: "User", foreign_key: "borrower_id"
validates :borrower_id, presence: true
end
这是我对 GroupTransactionsController 新操作的看法:
<%= provide(:title, "New group transaction") %>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_with(model: [@group, @group_transaction],url:
group_group_transactions_path,class: "new_transaction") do |f| %>
<!-- show error messages render error partial -->
<%= render "shared/error_group_transactions" %>
<%= hidden_field_tag "group_transaction[issuer_id]", current_user.id %>
<%= f.fields_for :group_transaction_borrowers do |borrower| %>
<%= borrower.label :borrower_id, "Borrower name" %>
<%= borrower.collection_select(:borrower_id, group_members(@group.id), :id, :name,
{ include_blank: 'Please select borrower' }) %>
<% end %>
<%= label_tag :value, "Value" %>
<%= f.number_field :value, step: 0.01 %>
<%= label_tag :description, "Description" %>
<%= f.text_field :description %>
<%= f.submit "Make Transaction!", class: "btn btn-primary" %>
<% end %>
</div>
_error_group_transactions 部分:
<% if @group_transaction.errors.any? %>
<div id="error_explanation">
<!-- show how many errors -->
<div class="alert alert-danger">
<%= pluralize(@group_transaction.errors.count, "error") %> occured
<!-- show the errors content -->
</div>
<ul>
<% @group_transaction.errors.full_messages.each do |msg| %>
<%= msg %>
<% end %>
</ul>
</div>
<% end %>
我使用嵌套路由,定义如下:
Rails.application.routes.draw do
#other routes
resources :groups do
resources :group_transactions, only: [:destroy, :show, :create, :new, :index]
end
end
当我提交带有空字段的表单时,我没有收到错误消息。但是似乎呈现了 _error_group_transactions 部分(检查日志信息如下)。我提交带有空字段的表单后的日志:
Started POST "/groups/6/group_transactions" for ::1 at 2020-10-18 16:46:04 +0200
(0.1ms) SELECT sqlite_version(*)
Processing by GroupTransactionsController#create as JS
Parameters: {"authenticity_token"=>"3GVrvgeGCZ/UMVy5He9LA3d96A5uchEeDknUxduNiuvQYJE2UDeyzarcOrApD2pYYSSMAHLzwBrE3acK9aBkhw==", "group_transaction"=>{"issuer_id"=>"21", "group_transaction_borrowers_attributes"=>{"0"=>{"borrower_id"=>""}, "1"=>{"borrower_id"=>""}}, "value"=>"", "description"=>""}, "commit"=>"Make Transaction!", "group_id"=>"6"}
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 21], ["LIMIT", 1]]
↳ app/helpers/session_helper.rb:27:in `current_user'
Group Load (1.0ms) SELECT "groups".* FROM "groups" WHERE "groups"."id" = ? LIMIT ? [["id", 6], ["LIMIT", 1]]
↳ app/controllers/group_transactions_controller.rb:77:in `get_group'
CACHE Group Load (0.0ms) SELECT "groups".* FROM "groups" WHERE "groups"."id" = ? LIMIT ? [["id", 6], ["LIMIT", 1]]
↳ app/controllers/group_transactions_controller.rb:81:in `how_many_members'
(0.7ms) SELECT COUNT(*) FROM "relations" WHERE "relations"."group_id" = ? [["group_id", 6]]
↳ app/controllers/group_transactions_controller.rb:81:in `how_many_members'
CACHE User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 21], ["LIMIT", 1]]
↳ app/controllers/group_transactions_controller.rb:21:in `create'
Rendering group_transactions/new.html.erb within layouts/application
<h2>Rendered shared/_error_group_transactions.html.erb (Duration: 16.8ms | Allocations: 551)</h2>
Rendered group_transactions/new.html.erb within layouts/application (Duration: 40.3ms | Allocations: 1051)
[Webpacker] Everything's up-to-date. Nothing to do
Rendered layouts/_shim.html.erb (Duration: 0.0ms | Allocations: 5)
Rendered layouts/_header.html.erb (Duration: 1.7ms | Allocations: 358)
Rendered shared/_flash_messages.html.erb (Duration: 0.1ms | Allocations: 17)
Rendered layouts/_footer.html.erb (Duration: 0.1ms | Allocations: 27)
Completed 200 OK in 508ms (Views: 217.4ms | ActiveRecord: 2.6ms | Allocations: 37732)
如果你愿意,我可以提供额外的代码。我将不胜感激您的任何帮助。在此先感谢,卢卡斯
解决方案
我将首先通过使用局部变量而不是实例变量来创建适当的通用错误部分:
# shared/errors.html.erb
<% if object.errors.any? %>
<div id="error_explanation">
<div class="alert alert-danger">
<%= pluralize(object.errors.count, "error") %> occured
</div>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
这会将您的部分内容从依赖于视图上下文状态的内容更改为一个简单的函数,您只需提供输入并呈现 HTML。因此,它可以呈现任何给定模型的错误。
然后渲染主对象的错误和每个嵌套对象的错误:
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_with(model: [@group, @group_transaction], url:
group_group_transactions_path, class: "new_transaction") do |f| %>
<%= render "shared/errors", object: f.object %>
<%= hidden_field_tag "group_transaction[issuer_id]", current_user.id %>
<%= f.fields_for :group_transaction_borrowers do |borrower| %>
<%# renders the errors for this borrower %>
<%= render "shared/errors", object: borrower.object %>
<%= borrower.label :borrower_id, "Borrower name" %>
<%= borrower.collection_select(:borrower_id, group_members(@group.id), :id, :name,
{ include_blank: 'Please select borrower' }) %>
<% end %>
<%= label_tag :value, "Value" %>
<%= f.number_field :value, step: 0.01 %>
<%= label_tag :description, "Description" %>
<%= f.text_field :description %>
<%= f.submit "Make Transaction!", class: "btn btn-primary" %>
<% end %>
</div>
推荐阅读
- python - 如何在不迭代查询集的情况下将 Django QuerySet 转换为包含对象列表的字典?
- python - 在 PyPDF PdfFileReader 中循环浏览页面范围会产生奇怪的循环
- php - 在 PHP 7.4 异常的源代码中包含 __wakeup 有什么意义?
- javascript - 在反应应用程序中更改数组中日期字段的格式
- reactjs - Material-UI 4.1.2 样式选择 SelectInput
- amazon-web-services - 如何与外部用户共享公共 S3 存储桶?
- javascript - 复选框处于活动状态时重复功能
- java - 如何将文件夹从 src/main/resources 复制到 Java 中的动态位置?
- javascript - JavaScript:将所有文本包装在一个跨度中的撇号之间
- autohotkey - Autohotkey 使我成为一个新的文本文件,但需要确认才能使它