Answer the question
In order to leave comments, you need to log in
How to display all subcategories when selecting a category?
There are three models - bookings, categories, subcategories.
Relationships between models:
Booking
belongs_to :category
belongs_to :subcategory
belongs_to :user
Category
has_many :subcategories
has_many :bookings
Subcategory belongs_to
:category
When creating an order, a category_id collection and a subcategory_id collection are selected.
But all categories and subcategories are selected.
How to implement the following - select a category and in the second collection_select display only subcategories of the selected category?
<%= f.collection_select :category_id, Category.all, :id, :title, {prompt: 'Select a category'} %>
<%= f.collection_select :subcategory_id, Subcategory.all, :id, :title, {prompt: 'Select a subcategory'} %>
Answer the question
In order to leave comments, you need to log in
If anyone needs:
view:
<%= f.collection_select :category_id, Category.all, :id, :title, {prompt: 'Select a category'} %>
<%= f.collection_select :subcategory_id, Subcategory.all, :id, :title, {prompt: 'Select a subcategory'} %>
update_sub_categories.js (in the same folder as the view):
$("#booking_subcategory_id").empty().append("<%= escape_javascript(render(: partial => 'subcategory', :collection => @cats, :as => :cat)) %>");
routes.rb:
get 'update_sub_categories' => 'bookings#update_sub_categories'
get 'bookings/update_sub_categories' => 'bookings#update_sub_categories'
controller:
respond_with(@cats)
end
_subcategory.html.erb:
<%= cat.title %>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question