RJS Rails进行表单验证

I have a form that I submit using the remote_form_for tag.

View

<% form_remote_tag(:url => { :action => 'create' })  do %>

a bunch of fields

<% end %>

Controller

def create 

  if @greeting.can_save?
   respond_to do |format|
   format.html {redirect_to board_link(@board)}
   format.js #close the iframe and reload the parent
   end
  else
   respond_to do |format|
   format.html {redirect_to :action => 'new'}
   format.js #show the errors on the form
   end
  end
end

create.rjs

page << "parent.$.fancybox.close();"

All works ok for the form being submitted with correct information. But I need to show error messages for invalid submissions.

How do I show the error messages on the form when the form does not pass validation?

Thanks in advance.

Pull the form out into it's own partial, render that partial in your page, giving the form a unique ID.

Within the form tags you should render the errors in any way you wish, whether this is listing them or adding classes to the affected fields.

Now do something like the following in your RJS:

if @greeting.valid?
  page << "parent.$.fancybox.close();"

else
  page.replace 'my_form_id', :partial => 'greetings/form'
end

That will re-render the form if there is an error. Make sure your @greeting instance variable is passed to this form so the fields are filled correctly.