Answer the question
In order to leave comments, you need to log in
How to correctly display the categories selected by the user?
There are users, users have categories of work performed, categories have subcategories in the same table, but with the parent_id of the parent category
, I did this:
User.rb
has_many :users_ecategories
has_many :ecategories, through: :users_ecategories
class UsersEcategory < ActiveRecord::Base
belongs_to :user
belongs_to :ecategory
end
class Ecategory < ActiveRecord::Base
has_many :users_ecategories
has_many :users, through: :users_ecategories
belongs_to :parent, class_name: 'Ecategory', foreign_key: 'parent_id'
end
<ul>
<% @user.ecategories.each do |ecategory| %>
<%= ecategory.parent.name %>
<li>
<ul>
<% @user.ecategories.where(parent_id: ecategory.parent.id).each do |sub_ecategory| %>
<li>
<%= sub_ecategory.name %>
</li>
</ul>
</li>
</ul>
<% end %>
<% end %>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question