首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails 5:用rails-ujs和jquery处理错误消息

Rails 5:用rails-ujs和jquery处理错误消息
EN

Stack Overflow用户
提问于 2018-05-12 11:20:35
回答 2查看 1.9K关注 0票数 1

在Rails 5.1.6中,我试图使用rails-ujs和jquery处理表单的错误消息。

lot.rb

代码语言:javascript
复制
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

代码语言:javascript
复制
...
  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响应中看到:

代码语言:javascript
复制
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

代码语言:javascript
复制
<%= 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

代码语言:javascript
复制
$('#new_lot').remove();
$('#new_lot_link').show();
$('#lots').prepend('<%= j render(@lot) %>')

application.js

代码语言:javascript
复制
//= 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;
});

出什么事了?感谢您的任何解释,特别是解决方案(;

EN

回答 2

Stack Overflow用户

发布于 2018-05-12 19:53:49

就像地球上最后一个人,我在自言自语

我解决了这个问题。也许有人也会感兴趣。

代码语言:javascript
复制
$(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);
});
票数 3
EN

Stack Overflow用户

发布于 2019-04-08 17:25:48

这边怎么样?它是不干净的,因为在js文件中有一些控制器的工作,但它对我是有效的。我也找不到其他容易的方法。

create.js.erb

代码语言:javascript
复制
<% 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分部中显示错误。

代码语言:javascript
复制
<% 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的其他部分

代码语言:javascript
复制
...
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包装表单

代码语言:javascript
复制
<div id="new_lot_form">
  <%= render 'form', lot: @lot %>
</div>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50305657

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档