D
D
dexdev2014-09-06 16:57:07
Ruby on Rails
dexdev, 2014-09-06 16:57:07

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

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
  	has_many :ecategories, class_name: 'Ecategory', foreign_key: 'parent_id'
end

I specify in the view
<% @user.ecategories.each do |ecategory| %>
                    <%= ecategory.parent_id.name %>
                    <%= ecategory.name %>
<% end %>

The question is, I can not figure out how to pull out the name of the parent category!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vsuhachev, 2014-09-06
@AdilA

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

And in the view, refer to parent, not parent_id (this is the ID of the parent record, number)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question