问题
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