Answer the question
In order to leave comments, you need to log in
How to pull out categories from the database that have a parent_id?
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
has_many :ecategories, class_name: 'Ecategory', foreign_key: 'parent_id'
end
<% @user.ecategories.each do |ecategory| %>
<%= ecategory.parent_id.name %>
<%= ecategory.name %>
<% end %>
Answer the question
In order to leave comments, you need to log in
You described the connection incorrectly, in the class you need to write something like this
class Ecategory < ActiveRecord::Base
belongs_to :parent, class_name: 'Ecategory'
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question