How to do complex server-side validation using jQuery / Ajax (and Rails)?

I am creating a Q&A application for Rails with many complex checks (for example, a user cannot vote on his own questions or vote on the same question twice, etc.). I use Ajax + JQuery to update the information on the page if the request passes, but you want to flash useful error messages if there are problems. While I have no problems with client side checks, for example, to check if a field is empty, the best I can do for something like voting on your own question is to prevent any javascript executed in the Votes controller so that the vote counter is not updated. Like this:

if @vote.save respond_to do |format| format.html {redirect_to :back} format.js end else respond_to do |format| flash[:error] = "Sorry, there was an error." format.html {redirect_to :back} end 

end

StackOverflow gives me an error message if I try to vote for my own question, so I know that it can be done!

thanks

+4
source share
2 answers

Server side validation

In your voting model:

 validates_uniqueness_of :current_user 

Save your traditional controller for editing and saving.

And then using jquery use this:

 $(".vote_link").submit(function(){ $.ajax({type: "POST", url: $(this).attr("action"), data: $(this).serialize(), dataType: "script", error: function(){ $("#message").show().html("You can't vote on this!")}, success: function(){ $("#message").show().html("You voted!")}; }); return false; }); 

And your HTML / HAML:

 = link_to 'Vote on This', new_vote_path(object) 
+1
source

Save your validations, generate innerHTML 'd HTML code for javascript sent back to the response, for example (using jQuery):

votes / create.js.erb:

 <% if @vote.errors %> $('#vote_form').html("<%= escape_javascript(render(:partial => 'form').html_safe) -%>"); <% else %> $('#vote_form').html("<%= escape_javascript(render(:partial => 'success').html_safe) -%>"); <% end %> 

This will save you a headache.

+1
source

All Articles