我正在尝试在Rails应用程序的表单元素下方内联显示错误消息。
我做了以下事情。
控制器
def create
@faculty = Faculty.new(faculty_params)
respond_to do |format|
if @faculty.save
format.html { redirect_to admin_faculties_path, notice: 'Faculty was successfully created.'}
format.json {render json: @faculty, status: :created, location: @faculty}
else
format.html {render '_form'}
format.json {render json: @faculty.errors, status: :unprocessable_entity }
end
end
end
表格
<% form_with(model: [:admin, @faculty]) do |f| %>
<div class="card-title">Add Faculty</div>
<div class="form-group">
<%= f.label :faculty_name, class: "form-label" do %>
Faculty Name <span class="form-required">*</span>
<% end %>
<%= f.text_field :faculty_name, class: "form-control", placeholder: "Faculty Name", required: true %>
</div>
<%= f.submit class: "btn btn-primary" %>
由于我在Model中有一些验证规则,因此它会检查验证,并在验证发生时阻止表单提交。因此,这是form_with表单,所有请求均由Ajax处理。因此,我希望在每个表单元素下方显示验证错误。请通过示例向我提出建议,以便我可以完成此任务。
答案 0 :(得分:0)
您可以在表单字段中检查每个属性的errors,如果该属性有任何错误,只需显示它们
<% form_with(model: [:admin, @faculty]) do |f| %>
<div class="card-title">Add Faculty</div>
<div class="form-group">
<%= f.label :faculty_name, class: "form-label" do %>
Faculty Name <span class="form-required">*</span>
<% end %>
<%= f.text_field :faculty_name, class: "form-control", placeholder: "Faculty Name", required: true %>
<% if @faculty.errors[:name].any? %>
<ul>
<% @faculty.errors[:name].each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
<% end %>
</div>
<%= f.submit class: "btn btn-primary" %>
一个更好的解决方案可以重构为helper:
助手
module FacultyHelper
def inline_errors(model, model_attribute)
result = ""
if model.errors[model_attribute].any?
model.errors[model_attribute].each do |message|
result += "<li>#{message}</li>"
end
end
return "<ul>#{result}</ul>".html_safe
end
end
查看 [更新:名称错误的包装器]
<% form_with(model: [:admin, @faculty]) do |f| %>
<div class="card-title">Add Faculty</div>
<div class="form-group">
<%= f.label :faculty_name, class: "form-label" do %>
Faculty Name <span class="form-required">*</span>
<% end %>
<%= f.text_field :faculty_name, class: "form-control", placeholder: "Faculty Name", required: true %>
<div id="user_name_errors">
<%= inline_errors(@faculty, :name) %>
</div>
</div>
<%= f.submit class: "btn btn-primary" %>
对于远程:true,您需要在控制器上定义format.js
控制器
def create
@faculty = Faculty.new(faculty_params)
respond_to do |format|
if @faculty.save
format.html { redirect_to admin_faculties_path, notice: 'Faculty was successfully created.'}
format.json {render json: @faculty, status: :created, location: @faculty}
format.js
else
format.html {render '_form'}
format.json {render json: @faculty.errors, status: :unprocessable_entity }
format.js
end
end
end
创建相应的js.erb视图
create.js.erb
$("#user_name_errors").html("<%= inline_errors(@faculty, :name) %>");