В 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
end
lots_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"
Вопрос в том, как сделать этот ответ json с помощью rails-ujs?
_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;
});
Что происходит не так? Спасибо за любое объяснение и особенно за решение (;