在Rails 5.1.6中,我试图使用rails-ujs和jquery处理表单的错误消息。
lot.rb
class Lot < ActiveRecord::Base
belongs_to :user
mount_uploader :lot_image, LotImageUploader
serialize :lot_images, JSON # If you use SQLite, add this line.
default_scope -> { order('created_at DESC') }
validates_processing_of :lot_image
validate :image_size_validation
validates :price, :lot_image, :description, presence: true
private
def image_size_validation
errors[:lot_image] << "should be less than 5MB" if lot_image.size > 5.megabytes
end
endlots_controller.rb
...
def index
@lot = current_user.lots.build
@lots = current_user.lots.paginate(page: params[:page])
end
...
def create
@lot = current_user.lots.create(lot_params)
respond_to do |format|
if @lot.save
format.html { redirect_to @lot, notice: 'Lot was successfully created.' }
format.json { render :show, status: :created, location: @lot }
format.js
else
#format.html { render action: "new" }
format.json { render json: @lot.errors.full_messages, status: :unprocessable_entity }
end
end
end
...正如预期的那样,当我提交无效的表单时,我在浏览器控制台422状态和json响应中看到:
0."Price can't be blank"
1."Lot image can't be blank"
2."Description can't be blank"问题是如何使用rails-ujs来呈现这个json响应?
_form.html.erb
<%= form_with(model: @lot, remote: true, id: :new_lot) do |form| %>
<div id="errors"></div>
<%= tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token) %>
<%= form.label :description, class: "label label-default" %>
<%= form.text_area :description, class: "form-control", id: :lot_description, autofocus: true %>
<%= form.label :price, class: "label label-default" %>
<%= form.text_field :price, class: "form-control", id: :lot_price %>
<%= form.label :lot_image, class: "label label-default" %>
<%= form.file_field :lot_image, id: :lot_lot_image %>
<p class="help-block">image must be present, less than 5 Mb.</p>
<%= form.submit "create a lot", class: "btn btn-default", data: { "disable-with": "Saving..." } %>
<% end %>create.js.erb
$('#new_lot').remove();
$('#new_lot_link').show();
$('#lots').prepend('<%= j render(@lot) %>')application.js
//= require jquery
//= require rails-ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require bootstrap
//= require_tree .
$(document).on("ajax:error", function(event) {
var detail = event.detail;
var data = detail[0], status = detail[1], xhr = detail[2];
var errors, message, results;
errors = xhr.responseJSON.error;
results = [];
for (message in errors) {
results.push($('#errors ul').append('<li>' + errors[message] + '</li>'));
}
return results;
});出什么事了?感谢您的任何解释,特别是解决方案(;
发布于 2018-05-12 19:53:49
就像地球上最后一个人,我在自言自语
我解决了这个问题。也许有人也会感兴趣。
$(document).on("ajax:error", function(event) {
var detail = event.detail;
var data = detail[0], status = detail[1], xhr = detail[2];
var errors = JSON.parse(xhr.responseText);
var er ="<ul>";
for(var i = 0; i < errors.length; i++){
var list = errors[i];
er += "<li>"+list+"</li>"
}
er+="</ul>"
$("#errors").html(er);
});发布于 2019-04-08 17:25:48
这边怎么样?它是不干净的,因为在js文件中有一些控制器的工作,但它对我是有效的。我也找不到其他容易的方法。
create.js.erb
<% if !@lot.errors.any? %>
$('#new_lot').remove();
$('#new_lot_link').show();
$('#lots').prepend('<%= j render(@lot) %>')
<% @lot = Lot.new %>
<% end %>
$("#new_lot_form").html("<%= j (render 'form', lot: @lot) %>")确保在_form.html.erb分部中显示错误。
<% if lot.errors.any? %>
<%= render 'shared/error_messages', object: form.object %>
<% end %>当您用@lot变量从create操作重新加载表单时,它会显示错误信息。如果没有错误,它将追加新的记录,并需要设置新的@lot变量<% @lot = Lot.new %>,因为否则表单将得到已保存的对象,下一次将发送您进行更新操作。
在lots_controller.erb中将format.js添加到if @lot.save的其他部分
...
respond_to do |format|
if @lot.save
format.html { redirect_to lots_path, notice: 'Lot was successfully created.' }
format.json { render :show, status: :created, location: @lot }
format.js
else
format.html { render :index }
format.json { render json: @lot.errors, status: :unprocessable_entity }
format.js
end
end
...在index.erb上用div#new_lot包装表单
<div id="new_lot_form">
<%= render 'form', lot: @lot %>
</div>https://stackoverflow.com/questions/50305657
复制相似问题