Parsing JSON errors using simple_form and AJAX in rails

别来无恙 提交于 2019-12-22 00:40:34

问题


I have a form that is using Simple Forms and remote => true on the users dashboard (which is handled by a dashboard view and dashboard controller). The form allows a user to add a custom game rule; however, it's loading the form via a Jquery's .load() function. The form is loading from the "rules" view (handled by a rules controller).

When the user clicks the submit button, I'm not getting any error validation.

Her is the create action on the rule controller:

def create
  @rule = Rule.new(params[:rule])

  respond_to do |format|
    if @rule.save
      format.html { redirect_to dashboard_path, notice: 'Rule was successfully created.' }
      format.json { render json: @rule, status: :created, location: @rule }
      format.js
    else
      format.html { render template: 'dashboard/index'}
      format.json { render json: @rule.errors, status: :unprocessable_entity }
      format.js
    end
  end
end

I've got a js file called create.js.erb in my views folder that is currently empty. I think that I have to somehow parse the JSON error data in this create.js.erb file, but I have no idea how to do it.

Also, does it matter that this form is being called by the Dashboard view/controller but the form is being handled by the Rule controller?


回答1:


Try the following inside create.js.erb

$('.error-messages').remove();
<% if @rule.errors.any? %>
  $('body').append('<ul class="error-messages"></ul>');
  <% @rule.errors.full_messages.each do |msg| %>
    $('.error-messages').append('<%= escape_javascript msg %>');
  <% end %>
<% end %>

This will append the errors in your body tag.



来源:https://stackoverflow.com/questions/15444473/parsing-json-errors-using-simple-form-and-ajax-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!