0
votes

in my app users has_many categories, categories have sub_categories in db i create parent_id with main category id

and now i dont know how correctly show main category if user select only sub_category User.rb

has_many :users_ecategories
  has_many :ecategories, through: :users_ecategories

Category.rb

class Ecategory < ActiveRecord::Base

has_many :users_ecategories
has_many :users, through: :users_ecategories
has_many :ecategories, class_name: 'Ecategory', foreign_key: 'parent_id'

end

Users_categories.rb

class UsersCategory < ActiveRecord::Base 
belongs_to :user 
belongs_to :ecategory 
end

views/user/show.html.erb

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

if user select child 1 and child 2 rails dublicate records and show something like this: category 1 child 1 child 2 category 1 child 1 child 2

but i need if user select child 1 and child 2 rails given only category 1 child 1 child 2

Thanks

1
There is a gem that fit well enough in this case: github.com/collectiveidea/awesome_nested_setJozsef NYITRAI

1 Answers

0
votes

You could try grouping:

<% @user.ecategories.group_by{|e| e.parent_id}.each do |parent, ecategories| %>
    <%= Parent.find(parent).name %>
        <!-- whatever Parent is, could be Category, Ecategory, I don't know -->
    <% ecategories.each do |ecategory| %>

etcetera