Rails AJAX Error message
I have a form that is being submitted via jQuery AJAX...
The model has a validates_presence_of for a field, if that field is blank, rails spits back over XHR :role_idNot Defined.
I learned how to customize that by doing:
validates_presence_of(:role_id, :message=> "Select a role to continue.")
But that spits back :role_IDSelecta role to continue. So I found this which might help, IDK yet:
<% errors.each do |attribute, message| -%>
<% if message.is_a?(String)%>
<li><%= message %></li>
<% end %>
<% end -%>
My question is how do I handle this type of back and forth with a remote form in Rails 3? I want to submit with AJAX and somehow send back the error me开发者_如何学编程ssage with AJAX?
Ideas? Plugins?
Thanks again
Well... it's not Rails that's doing the spitting back. It's your controller. So when your model fails validation, you can spit anything you like. You probably have a create and an update method, and each must handle XHR. It's important you decide for yourself how you want to communicate with the browser.
One might argue that failing validation should create an error (4xx) response, but that's really an HTTP, not an application response code. In this case, your application handled the request properly so it needs to return a 200. So the Ajax error handler won't be of much use to you -- that's for real page-not-found, server hosed, etc. errors.
Rather, your success handler needs to examine the flash hash to discover whether errors are present, and if so to put the error text in some relevant location on the page for your user.
One plugin that looked promising was Stickies (http://github.com/JokerCatz/stickies). There hasn't been any activity on the project in a while, but if it's not working with your version of Rails, it shouldn't be too hard to fork it and bring it up to current Rails levels.
精彩评论