Search code examples
ruby-on-railsrubyruby-on-rails-4forum

Creating a Rails forum, how would i create a sub category crud which can link through itself


At the moment I have categories > posts > comments, and can CRUD the categories, within the categories I can CRUD the Posts (which are specific to categories) and within the Posts I can CRUD the comments, What I now want to be able to do is CRUD Sub-Categories within the Categories, But also CRUD Sub-Categories within Sub-Categories continuously.

So I am really not sure where to start, My thinking is I need to create a model that checks to see if there's a category_id, and if not to check the sub-category_id or something alone these lines?

Any help is appreciated.

Longshanks


Solution

  • First of there is no subcategories by itself. A sub-category is a category with a parent, and that is the clue.

    First of you need to add the relation to the model:

      belongs_to :parent, :class_name => 'Category', :foreign_key => :parent
      has_many :children, :class_name => 'Category', :foreign_key => :parent
    

    Then in your migration:

      add_field :categories, :parent_id, :integer
    

    And now you will have the:

      childrens = Category.first.children
      parent = childrens.first.parent
    

    Available anywhere.

    Feel free to rename the children-parent relation as you please but change everything else related.