Home > Mobile >  How to relate categories with subcategory i.e. tag in rails 7?
How to relate categories with subcategory i.e. tag in rails 7?

Time:09-01

I am learning ruby on rails and i am creating a blogger app. In which i have many users and users can have many blogs. Now I want to create blogs on the basis of category. But i also want category having subcategory i.e tag. On the basis of category and subcategory user can search blogs. If there is no subcategory then it'll insert into subcategory.

CodePudding user response:

if you want to keep things in separate tables then you can have a chain of association between models like this:

User Model:

class User < ApplicationRecord
  has_many :posts
end

Post Model:

class Post < ApplicationRecord
  belongs_to :user
  belongs_to :category
end

Category Model:

class Category < ApplicationRecord
  has_many :posts
  has_many :subcategories
end

SubCategory Model

class SubCategory < ApplicationRecord
  belongs_to :post
end

CodePudding user response:

I would make a new model for the categories. That new model could have Self-Referential Associations to itself, so you could associate sub-categories (what I called children below) or parent categories.

class Category < ActiveRecord::Base
  belongs_to :parent, class_name: 'Category'
  has_many :children, class_name: 'Category', foreign_key: 'parent_id'
end

This would leave the flexibility to add associations to users, depending if you want the categories belong to users or if they are across the app.

  • Related