DEV Community

Brittany
Brittany

Posted on

Day 67 - #100DaysofCode - Adding Categories to Rails App

I spent the day trying to add categories to my rails application. I am still in the process of adding some other functionality, like the nested route portion of it. However, so far, I was able to create a migration and make sure that post belong to a category and that a category can have many posts. In addition, I was able to create a drop down for each category on the posts index page.

Schema

categories

 create_table "categories", force: :cascade do |t| t.string "name" t.text "desc" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end 
Enter fullscreen mode Exit fullscreen mode

posts

create_table "posts", force: :cascade do |t| t.string "title" t.text "description" t.integer "user_id" t.integer "category_id" end 
Enter fullscreen mode Exit fullscreen mode

Models

post.rb

 #Categories section belongs_to :category 
Enter fullscreen mode Exit fullscreen mode

category.rb

class Category < ApplicationRecord has_many :posts end 
Enter fullscreen mode Exit fullscreen mode

Views

<%= form_tag posts_path, method: :get do %> <p> <%= select_tag "category_id", options_from_collection_for_select(Category.all, "id", "name"), {:include_blank => 'Search By Category'} %> <%= submit_tag "Search", name: nil, :class => "myButton" %> </p> <% end %> 
Enter fullscreen mode Exit fullscreen mode

Controller

Posts Controller

if @category = params[:category_id] @posts = Post.where(category_id: @category) render 'index' else @post = Post.all @categories = Category.all end end 
Enter fullscreen mode Exit fullscreen mode

I need to refactor my code so that Post.where(category_id: @category) is in my model, instead of my posts controller, but my categories functionality seems to be coming together. I will work on it more and share the final code in the near future.

As always, thanks for reading!

Sincerely,
Brittany

Song of the day: Yet, another throwback

Top comments (0)