0

I am submitting form with data-remote=true attribute. The create action in the controller looks like:

format.js { @user }

and it is handled by the following template:

create.js.erb

Is there an easy way to render the @user.errors messages like JSON in order to used the following JSON in the current template and handle the errors then?

I know that I can render the errors using format.json directive but I want to make and other JavaScript manipulation, not only render the errors and because of this I am using the format.js tehnique.

4

1 回答 1

0

This easily can be solved by using to_json method. In order to render the passed model object I only should do:

var current_errors = <%=  @security_user.errors.to_json %>;

Anyway, this was still not rendering a proper JSON because the quotes were being automatically encoded by rails (to prevent XSS), so you should use one of the following methods:

  1. html_safe
  2. raw
  3. h

More information about them can be found here - raw vs. html_safe vs. h to unescape html

And the final solution that works for me is:

var current_errors = <%=  raw @security_user.errors.to_json %>;
于 2013-06-18T20:05:41.883 回答