A good example of how rails respond to work with model validation errors and ajax form

What I want

I am using new response_to Controller Api rails with ajax form. If the object does not check the rails, it returns a Json error object and fires the "ajax: error" event. I want to show each error in the next / in the corresponding form field (we use formatting).

Here is my example ..

controller:

class Admin::PrivateMessagesController < AdminController respond_to :json def create private_message = PrivateMessage.new(params[:private_message]) private_message.save respond_with private_message end end 

view

 <%= form_for @private_message, :remote => true, :html => {"data-type" => "json"} do |f| f.input :body ... end %> 

JS / CoffeeScript

I just add all the error to the line and show it.

 $("#new_private_message").on 'ajax:error', (event, data, status) -> error = "Errors: " $.each $.parseJSON(data.responseText), (field, errorMessage) -> error += "#{field}-#{errorMessage} " $('#errors').html(error) 

json error object

 {"body":["Please enter a message."],"subject":["Please enter a message."]} 

my questions!

  • Do I need to parse json myself?
  • How can I add an error message to the field?
  • Should it be part of standard jquery-ujs?
+4
source share
1 answer

do i have to parse the json myself?

Yes, error responses are not handled by the jQuery Ajax API automatically. You have to do it yourself.

how can i add the error message to the field?

Here is a very quick error handling example: http://jsfiddle.net/hpM6W/

Although a much more comprehensive solution is required. For example, in the example I presented, list twice and see what happens ...

There are many toolkits and libraries for reliable client-side validation and error reporting. I highly recommend looking at the jQuery validation plugin to get started with form validation. You should always perform server side validation and return any errors.

What I did in the past is a hybrid model in which I would do client-side validation as a user-friendliness (better user interface), and also use the jQuery validation plugin to render the server-side validation result using the showErrors method.

Here is a quick example: http://jsfiddle.net/GNq84/ on how to use showErrors to display received error messages from server side validation. Note that in this example, multiple jobs work much better.

However, there is one caveat. showErrors expects these errors: { "element": "message" } , and not what you have: { "element": [ "message1", "message2" ] } , but I will leave this to you to solve: )

+2
source

Source: https://habr.com/ru/post/1397920/


All Articles