1.我**视图/演出/ new.html.erb我使用显示所选类别的子类别中的Rails 4
<%= f.collection_select :category_id, Category.all, :id, :name, {prompt: "Choose a category"} %>
<%= f.collection_select :subcategory_id, Subcategory.all, :id, :name, {prompt: "Choose a subcategory"} %>
它创建这个
并点击下面的图片:
从上面的图片可以看出,根据我选择的类别,只显示该类别拥有的子类别。
2.在我的这个工作的演出控制器,我写了下面的代码。
def update_sub_categories
@cats = Subcategory.where(category_id: params[:category_id]).all
respond_with(@cats)
end
我曾在同一文件夹中创建一个文件视图/演出/ update_sub_categories ,并把这个代码
$("#gig_subcategory_id").empty().append("<%= escape_javascript(render(:partial => "subcategory", :collection => @cats, :as => :cat)) %>")
而且部分在同一文件夹v IEW /gigs/_subcategory.html.erb
<option value="<%= cat.id %>"><%= cat.name %></option>
4.添加在应用程序/ JavaScript的/ gigs.js.coffee
$(document).on 'change', '#gig_category_id', (evt) ->
$.ajax 'update_sub_categories',
type: 'GET'
dataType: 'script'
data: {
category_id: $("#gig_category_id option:selected").val()
}
error: (jqXHR, textStatus, errorThrown) ->
console.log("AJAX Error: #{textStatus}")
success: (data, textStatus, jqXHR) ->
console.log("Dynamic country select OK!")
5.终于在路线
get 'gigs/update_sub_categories' => 'gigs#update_sub_categories'
问:一切正常,我选择了所选类别的类别和子类别,但它仅在有效views/gigs/new.html.erb,并没有在views/gigs/edit.html.erb,我做错了什么?
你的'edit.html.erb'包含了什么?你的意思是什么不起作用? – Pavan