1

In my Rails 3 app I have the following partial to display error messages in the main layout:

<% flash.each do |name, msg| %>
  <% if msg.is_a?(String) %>
    <div class="alert alert-<%= name == :notice ? "success" : "error" %>">
      <a class="close" data-dismiss="alert">&#215;</a>
      <%= content_tag :div, msg, :id => "flash_#{name}" %>
    </div>
  <% end %>
<% end %>

I am using JQuery to call create method and created a create.js.erb which is run succesfully after creating the model or after validating with errors.

The question is: how do I go about displaying the list of validation errors in my partial from create.js.erb file? Or ... can that be done from the controller?

Thanks

1 Answer 1

3

Try this in your create.js.erb,

<% if @your_variable.errors.count > 0 %> #your_variable is the variable you declared in your controller
  $('.new-user-form').html("<%= escape_javascript(render 'form')%>"); # new-user-form is the class name of the div that had the form
<% else %>
  window.location.href='<%= url_for(:action => :index) %>'
<% end %>

In this case that your form is a partial with the div like the following:

<%= form_for(@your_variable, :remote => true) do >
  ....
<% end %>

<div class="new-user-form"> # In your index or any page that you called that partial
</div>

And you need to add format js in your create action in the controller

If you provide more code, I can specify the exact thing. It's just an idea for you to do.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.