--List the contents associated with each category created by Active Hash
--Set up routing --Make a link --Write the action in the controller --Create the corresponding view
As a prerequisite, it is assumed that the installation of Active Hash and the settings around the model / DB have been completed.
Since the Item model has category_id, set the routing as follows
routes.rb
get '/items/category/:id', to: "items#category"
Make a link.
html.erb
link_to 'hoge', '/items/category/1'
link_to 'fuga', '/items/category/2'
link_to 'piyo', '/items/category/3'
By the way, the Category model is set like this
models/category.rb
class Category < ActiveHash::Base
self.data = [
{ id: 1, name: 'hoge' },
{ id: 2, name: 'fuga' },
{ id: 3, name: 'piyo' }
]
end
category Defines an action.
items_controller.rb
def category
@item = Item.find_by(category_id: params[:id])
@items = Item.where(category_id: params[:id]).order('created_at DESC')
end
@Item is defined to display the category name on the category list page, and @items is defined to expand with each.
Create category.html.erb under items.
ruby:items/category.html.erb
#Display of category name
@item.category.name
#Expand the contents of the category
@items.each do |item|
~ Omitted ~
end
I think I could write it quite easily by passing each id with link_to. Please let me know if there is a better way!
✔︎
Recommended Posts