我正在尝试使用 AJAX 呈现表单。非 ajax 版本可以正常工作,但 ajaxified 版本不能。它的链接在 index.html.erb 中。Webrick 服务器显示:
在 2012-11-19 17:19:27 -0500 开始 GET "/categories/3/new_sub" for 127.0.0.1
由 CategoriesController#new_sub 作为 JS
参数处理:{"id"=>"3"}
类别负载(0.1 ms) SELECT "categories".* FROM "categories" WHERE "categories"."id" = ? LIMIT 1 [["id", "3"]]
渲染类别/_form.html.erb (1.8ms)
渲染类别/new_sub.js.erb (3.6ms)
8ms 内完成 200 OK (Views: 6.3ms | ActiveRecord: 0.1毫秒)
这是我的类别控制器:
# 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 助手:
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 %>