在我的任务显示页面中,我有用于创建响应的表单,此处也显示了响应。 (任务有很多回复)
视图\任务\ show.html.erb
<%= simple_form_for([@task, Response.new]) do |f| %>
<%= f.input :is_comment, as: :hidden %>
<%= f.input :negotiate_pay, label: false %>
<%= f.input :comment_text, as: :text, input_html: {rows: 3}, label: false %>
<div class="row">
<div class="col-md-4 col-md-offset-8">
<%= f.button :submit %>
</div>
</div>
</div>
<% end %>
<br>
<div id="comments">
<%= render @responses %>
</div>
控制器\ tasks_controller
def show
@task = Task.find(params[:id])
@responses = @task.responses.all
end
控制器\ responses_controller
def create
@task = Task.find(params[:task_id])
@response = @task.responses.create(response_params)
@response.user_id = current_user.id
@response.is_comment = params[:is_comment]
@response.save
respond_to do |format|
format.html { redirect_to @task }
format.js
end
end
它工作正常但在验证和提交后它没有显示表单中的错误。如何在任务的显示页面中的响应表单中显示错误消息。我正在使用simple_form btw。
请帮助
编辑:
型号: 模型\ response.rb
belongs_to :user
belongs_to :task
has_many :subcomments
default_scope -> { order('created_at DESC') }
#VALIDATIONS
validates :comment_text, presence: true
validates :negotiate_pay, presence: true
答案 0 :(得分:0)
您需要添加将向您的表单显示错误的代码:
<%= simple_form_for([@task, Response.new]) do |f| %>
<% if @response.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@response.errors.count, "error") %> prohibited this response from being saved:</h2>
<ul>
<% @response.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
您还需要调整responController中的create
操作:
def create
@task = Task.find(params[:task_id])
@response = @task.responses.build(response_params)
@response.user_id = current_user.id
@response.is_comment = params[:is_comment]
respond_to do |format|
if @response.save
format.html { redirect_to @task, notice: "response was createad" }
format.js
else
format.html { render :show }
end
end
还要确保在application.html.erb中显示错误:
<% if flash[:error] -%>
<p class='alert alert-danger'><%=h flash[:error] %></p>
<% end -%>
<% if flash[:notice] -%>
<p class='alert alert-success'><%=h flash[:notice] %></p>
<% end -%>