Q:

How do I perform complex, server-side form validation with JQuery/Ajax (and Rails)?

I'm building a Q&A app on Rails with a lot of complex validations (e.g. a user can't vote on his/her own questions, or vote on the same question twice, etc). I've been using Ajax+JQuery to update things on the page if the request goes through, but want to flash helpful error messages if there are problems. While I have no problem with client-side validations like checking to see if a field is blank, the best I can do for something like voting on your own question is prevent any javascript from being executed in the Votes controller, so that the votes counter doesn't update. 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 up my own question, so I know it can be done!
Thanks

A:

Server Side Validation
In your Vote model :
validates_uniqueness_of :current_user

Keep your traditional controller set up for edit and save.
And then with 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)

