A
A
Andrey Korablin2015-11-18 15:12:34
JavaScript
Andrey Korablin, 2015-11-18 15:12:34

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

2 answer(s)
A
Andrey Korablin, 2015-12-08
@monaxide

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 %>

S
Sworg, 2015-11-18
@Sworg

Alternatively, when choosing the first collection_select, send an ajax request to the server with the category_id parameter, which will return, for example, json of all subcategories. And only then insert them using JS into the form.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question