Tommy Duek
Tommy Duek

Reputation: 51

Can't get AJAX form partial working on Rails 3.2

I'm trying to render a form with AJAX. The non-ajax version works fine, but the ajaxified version doesn't. The link to it is in the index.html.erb. The Webrick server shows:

Started GET "/categories/3/new_sub" for 127.0.0.1 at 2012-11-19 17:19:27 -0500
Processing by CategoriesController#new_sub as JS
Parameters: {"id"=>"3"}
Category Load (0.1ms) SELECT "categories".* FROM "categories" WHERE "categories"."id" = ? LIMIT 1 [["id", "3"]]
Rendered categories/_form.html.erb (1.8ms)
Rendered categories/new_sub.js.erb (3.6ms)
Completed 200 OK in 8ms (Views: 6.3ms | ActiveRecord: 0.1ms)

Here's my Category controller:

# GET /categories
# GET /categories.json
def index
  @categories = Category.roots

  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @categories }
  end
end

# GET /categories/1/new_sub.html
# GET /categories/1/new_sub.js
def new_sub
  @parent = Category.find(params[:id])
  @category = Category.new

  respond_to do |format|
    format.html
    format.js
  end
end

index.html.erb:

<h1>Listing categories</h1>

<%= recurse_categories(@categories) %>

<br />

<%= link_to 'New Category', new_category_path %>

recurse_categories helper:

def recurse_categories(cats)
  s = "<ul>"
  cats.each do |cat|
    s << "<li id=\"#{cat.id}\">#{link_to cat.name, new_sub_category_path(cat), remote: true}</li>"
    if cat.has_children?
      s << recurse_categories(cat.children)
    end
  end
  s << "</ul>"
  s.html_safe
end

new_sub.js.erb:

$('ul').after(<%= render partial: "form", locals: { parent: @parent, category: @category } %>);

_form.html.erb:

<%= form_for(category) do |f| %>

  <div class="field">
    <%= f.text_field :name  %>
    <%= f.hidden_field :ancestry, value: "#{parent.ancestry + '/' + parent.id.to_s}" %>
    <%= f.submit "Create subcategory" %>
  </div>

<% end %>

Upvotes: 0

Views: 449

Answers (2)

Tommy Duek
Tommy Duek

Reputation: 51

Fixed it! I just forgot quotation marks around the jquery selector and parameter, DUH!

Upvotes: 0

ktcoder
ktcoder

Reputation: 111

Your "ul" tag is under category error's condition block. Are you sure you want to append your response in "error_explanation" div.

You can have an span tag and use it in new_sub.js.erb

<div class="field">

 <span id="subcat"/>     

<%= f.text_field :name  %>
<%= f.hidden_field :ancestry, value: "#{parent.ancestry + '/' + parent.id.to_s}" %>
<%= f.submit "Create subcategory" %>

Upvotes: 1

Related Questions