我正在尝试使用AJAX渲染表单。非ajax版本工作正常,但ajaxified版本没有。它的链接位于index.html.erb中。 Webrick服务器显示:
在2012-11-19 17:19:27 -0500开始获取127.0.0.1的GET“/ categories / 3 / new_sub”
由CategoriesController处理#new_sub为JS
参数:{“id”=>“3”}
类别加载(0.1ms)SELECT“categories”。* FROM“categories”WHERE“categories”。“id”=?限制1 [[“id”,“3”]]
渲染类别/ _form.html.erb(1.8ms)
渲染类别/ new_sub.js.erb(3.6ms)
8ms完成200 OK(浏览次数:6.3ms | ActiveRecord:0.1ms)
这是我的类别控制器:
# 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 %>
答案 0 :(得分:1)
您的“ul”标记位于类别错误的条件块下。您确定要在“error_explanation”div中附加您的回复吗。
您可以使用span标记并在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" %>
答案 1 :(得分:0)
修正了它!我忘了jquery选择器和参数DUH!
周围的引号