Ruby on Rails validation messages in RJA
This thing wasted my few hours and then finally I made it work. It’s very easy to show validation messages in Ruby on Rails on the page when It reloads after submitting the form. Just use one following line to show all the validation error messages.
<% form_for :model, :url => ‘url’ do |f| %>
<%= f.error_messages %> #print all the validation error messages
#here goes all of your other code for other fields
<% end %>
Now the question is how to show same validation in RJS while working with AJAX? error_messages does not work in RJS. You can access @model.errors array in RJS but it’s an array having all the error messages. You can use following code to print error messages in your RJS page to update original page view.
page.replace_html “error_messages”,@model.errors.full_messages.join(“<br>”)
Replace @model with your model name you are working with. Function full_messages will print all of your error messages but if you use join function and pass <br> as parameter then it will join all the error messages and add a line break in between.
Here is another way of using this error message. You can also store validation messages in a flash message and then use either in RJS or your view. Write following code in your controller action.
if @model.save
#when successfully saved
else
flash[:error] = @model.errors.each {|field, msg| error << msg + "<br>"}
end
that’s it!



