开发者

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

开发者 https://www.devze.com 2023-01-12 14:05 出处:网络
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 qu开发者_如何学运维estions, or vote on the same question twice, etc). I\'ve been using Aj

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 qu开发者_如何学运维estions, 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


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)


Keep your validations, generate HTML to be innerHTML'd into place with javascript sent back as a response, like so (with 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 %>

It'll save you some headache.

0

精彩评论

暂无评论...
验证码 换一张
取 消