我遵循Rails指南来实现这一点,但我得到这个错误,我不完全确定如何修复它。
错误显示形式:
<% if @group.errors.any? %>
<div id="error_exp">
<h2><%= pluralize(@group.errors.count, "error") %> prohibited this article from being saved:</h2>
<ul>
<% @group.errors.each do |error| %>
<li><%= error.full_message %></li>
<% end %>
</ul>
</div>
<% end %>
Controller create action:(我正在测试一个新的组表单上的错误显示)
def create
@group = current_user.groups.build(group_params)
if @group.save
redirect_to user_groups_path(current_user)
else
render :new
end
end
模型验证:
class Group < ApplicationRecord
has_many :cards, dependent: :destroy
belongs_to :category
belongs_to :user
end
class Category < ApplicationRecord
has_many :groups
has_many :users, through: :groups
validates :name, presence: true
validates_uniqueness_of :name, :case_sensitive => false
end
class Card < ApplicationRecord
belongs_to :group
validates :front,:back, presence: true
end
谢谢你的帮助!
Rails指南适用于6.1
。在此之前,errors.each
产生了|attribute,error|
, Rails 6.0和Rails 6.1
我假设你是低于6.1基于你的错误,在这种情况下你想使用:
<% @group.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>