我正在使用ajax-rails呈现我的表单,并且验证停止工作。当我单击以提交应进行验证的空白时,验证不会生效,并且后端日志显示其张贴了空白表格。如果我不使用ajax,它将正常工作。我不知道我在想什么。
模型
class ClockEntry < ApplicationRecord
belongs_to :user
validates :purpose, presence: true # I validated the attribute
end
index.html.erb
<div class="container" id="new-clock-entry">
<%= link_to 'New Clock Entry', new_clock_entry_path, remote: true, class: 'btn btn-primary btn-sm' %>
</div>
_form.html.erb
<%= simple_form_for clock_entry, remote: true do |f| %>
<%= f.error_notification %>
<%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>
<div class="form-inputs">
<%= f.input :purpose %>
</div>
<div class="form-actions">
<%= f.button :submit, class: 'btn btn-primary btn-block btn-lg' %>
</div>
<% end %>
new.html.erb
<h1>New Clock Entry</h1>
<%= render 'form', clock_entry: @clock_entry %>
<%= link_to 'Back', clock_entries_path %>
new.js.erb
$('#new-clock-entry a').hide().parent().append("<%= j render 'form', clock_entry: @clock_entry %>")
create.js.erb
$('#new-clock-entry form').remove();
$('#new-clock-entry a').show();
$('table#clock-entry tbody').append("<%= j render @clock_entry %>");
控制器
def new
@clock_entry = ClockEntry.new
end
def create
@clock_entry = current_user.clock_entries.new(clock_entry_params)
@clock_entry.set_time_in
respond_to do |format|
if @clock_entry.save
format.js { redirect_to root_path, notice: 'Clock entry was successfully created.' }
format.html { redirect_to @clock_entry, notice: 'Clock entry was successfully created.' }
format.json { render :show, status: :created, location: @clock_entry }
else
format.html { render :new }
format.json { render json: @clock_entry.errors, status: :unprocessable_entity }
end
end
end
答案 0 :(得分:0)
@arieljuod对我解决此问题非常有帮助。正如他首先提到的,我不是在create方法的format to respond to js
条件下询问我的else
。这就是我所做的:
控制器创建操作
将以下行添加到创建动作的else
条件中:
format.js {render:new}
所以我的控制器动作变为:
def create
@clock_entry = current_user.clock_entries.new(clock_entry_params)
@clock_entry.set_time_in
respond_to do |format|
if @clock_entry.save
format.html { redirect_to @clock_entry, notice: 'Clock entry was successfully created.' }
format.js { redirect_to root_path, notice: 'Clock entry was successfully created.' }
format.json { render :show, status: :created, location: @clock_entry }
else
format.js { render :new } # Added this...
format.html { render :new }
format.json { render json: @clock_entry.errors, status: :unprocessable_entity }
end
end
end
new.js.erb文件
然后在new.js.erb
文件中,呈现:new
表单后,您需要删除或隐藏已经存在的内容,并附加一个包含错误消息的新表单。因此,我必须通过在form tag to be hidden
中提供new.js.erb
来删除整个表单。因此,我将以下这一行添加到我的new.js.erb
文件中:
$('#new-clock-entry form')。hide()。parent()。append(“ <%= j render'form',clock_entry:@clock_entry%>”)
因此,新的new.js.erb
文件现在变为:
$('#new-clock-entry a').hide().parent().append("<%= j render 'form', clock_entry: @clock_entry %>")
$('#new-clock-entry form').hide().parent().append("<%= j render 'form', clock_entry: @clock_entry %>")
我认为这对于遇到相同问题的任何人都应该很方便。