0

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

<% @user.ecategories.each do |ecategory| %>
                    <%= ecategory.name %>
                    <%= ecategory.id %>
                <% end %>

how to show main category name? <%= ecategory.parent_id.name %> doesn't work please help

1 Answer 1

1

I think you need to define the parent relation

class Ecategory < ActiveRecord::Base
    has_many :users_ecategories
    has_many :users, through: :users_ecategories
    has_many :ecategories, class_name: 'Ecategory', foreign_key: 'parent_id'

    belongs_to :parent_ecategory, class_name: 'Ecategory', foreign_key: 'parent_id'

end

Then the call would be

<%= ecategory.parent_ecategory.name %>
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, i have only 1 question, if i use this <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> ecategory.parent_ecategory.name duplicated but i need one category and all selected sub_categories
Parent categoties are ones that don't have parents, so Ecategory.where(parent_id: nil) and @user.ecategories.where(parent_id: nil) are parent categories

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.