What i want
I use the new rails respond_to Controller Api with a ajax form. If an object does not validate rails returns a Json Error Object and triggers the "ajax:error" event. I want to show each error next/under the corresponding form field (we are using formatastic).
Here 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 error to a string and show them..
$("#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 have to parse the json myself?
- how can i add the error message to the field?
- Should it not be part of standard jquery-ujs?