D
D
dexdev2014-09-06 21:37:22
Ruby on Rails
dexdev, 2014-09-06 21:37:22

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

jointable
users_ecategory.rb
class UsersEcategory < ActiveRecord::Base
  belongs_to :user
  belongs_to :ecategory
end

ecategory.rb
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

in the view I specify:
<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 %>

but pulls out the following
Visitor
Privileged visitor
Simple visitor
Visitor
Privileged visitor
Simple visitor
, that is, pulls out the parent category twice, but it is necessary that once and under it the child ones, tell me how best to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Marat Amerov, 2014-09-06
@AdilA

try https://github.com/stefankroes/ancestry

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question