Search code examples
ruby-on-railsrubysimple-form

Ruby on Rails Categorization Via Simple_Form collections


Is what I am doing even practical or is there a much easier way to implement this category/sub-category system?

My categorization System

I have an app that has a posts table that will be organized by a blog_categories table. This categorization has main categories and sub-categories. blog_categories with parent_id as NULL are the main categories. sub-categories link to the main via a :string with the main's :name.

Assigning the categories to the post

I was trying to implement this using simple_form and wanted to have the dropdown selector, divide the collection of sub-categories based on the main category. I ran into the problem of only showing the first item in each array when I tried to make an array of arrays:

<%= f.input :category_id, prompt: "Select Category", collection: [
["No-category"],
["All News","Audio Industry","Game Audio","Film Audio"],
["All Reviews","Software","Hardware"],
["All Interviews","Sound Designers","Game Developers","Voice Talent"],
["All Tutorials","Sound Design","Composition","Implementation","Voice Acting"]
], input_html: { class: "form-control center" } %>

blog_category Modal:

class BlogCategory < ApplicationRecord
  has_many :posts

  # This is called a self referential relation. This is where records in a table may point to other records in the same table.
  has_many :sub_blog_categories, class_name: "Category", foreign_key: :parent_id
end

blog_categories Table:

t.string "name"
t.string "parent_id"

Post modal: belongs_to :blog_category

posts Table: t.string "category_id"

  1. Is there a different way of adding in groups/dividers in the dropdown?

  2. Should I even be taking this approach in assinging sub-categories?

  3. Will this even work when using main categories and sub categories?


Solution

  • I found a solution to assigning the category_id based on the BlogCategory.id selected from its :name by using the following simple_form input:

    <%= f.input :category_id, collection: BlogCategory.all, label_method: :name, value_method: :id , input_html: { class: "form-control center" } %>
    

    The BlogCategory.all pulls all of the categories that have been entered into the blog_category table.

    The label_method pulls the :name of each item in the blog_category table.

    The value_method assigns a value to all selections in the drop-down menu based on the .id of the respective fields :name from the blog_category table.