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
posts
create_table "posts", force: :cascade do |t|
t.string "title"
t.text "description"
t.integer "user_id"
t.integer "category_id"
end
Models
post.rb
#Categories section
belongs_to :category
category.rb
class Category < ApplicationRecord
has_many :posts
end
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 %>
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
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)