1. In my **view/gigs/new.html.erb i use
<%= 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"} %>
It creates this
and when clicked the below image:
From the picture above as you see depending on what category i choose,just the subcategories owned by that category are displayed.
2. In my gig controller for this to work,i wrote the below code.
def update_sub_categories
@cats = Subcategory.where(category_id: params[:category_id]).all
respond_with(@cats)
end
3. I had to create a file in the same folder view/gigs/update_sub_categories and put this code
$("#gig_subcategory_id").empty().append("<%= escape_javascript(render(:partial => "subcategory", :collection => @cats, :as => :cat)) %>")
Also the partial in the same folder view/gigs/_subcategory.html.erb
<option value="<%= cat.id %>"><%= cat.name %></option>
4. Add in App/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. Finally in routes
get 'gigs/update_sub_categories' => 'gigs#update_sub_categories'
Question: Everything works, i choose the category and the subcategory of the chosen category appear.But it works just in views/gigs/new.html.erb,and doesn't in views/gigs/edit.html.erb, what am I doing wrong?
Look in your console or development.log and you're going to see some message indicating that rails could not resolve
update_sub_categories
when your script fails. Wheras when calling that method with a new form, you'll see that rails is callingyour_controller/your_action/update_sub_categories
-- you can probably see where this is going now.You're going to have to update your
routes.rb
both to handle a "naked" call to the method (when it's missingyour_action
and for member routing. Explicit handling of member routing is necessary because your edit uses anID
field embedded in the route, rather than appending it at the end.Replace your current routing in
routes.rb
with the following and you should be in good shape:Obviously, you're going to want to substitute your model name for the string
your_model
in my example.