●期待する動作
categoriesコントローラのindexアクションから、showアクションに遷移して、投稿時のカテゴリーに結びついた投稿と記事を表示させたい。
indexアクションの表示まではできています。
indexアクション → 各カテゴリーをCategory.allで表示
●困っていること
paramsの受け渡し方がよく理解できていない為、showアクションのビューが表示できていない。
●教えていただきたいこと
①showアクションのparamsの設定の仕方、インスタンスをどのようにDBから引っ張って来ればいいか、②ビューの表示方法を教えていただきたいです。
わかる方いましたら、教えていただきたいです。よろしくおねがいします。
categoriesコントローラ
class CategoriesController < ApplicationController def index @categories = Category.all end def show @category= Category.find(params[:id]) @posts = @category.posts binding.pry end end
categories#index.html.erb
<%= @categories.each do |category|%> <%=link_to category.symptoms, category_path(category.id)%> <%end%>
categories#show.html.erb
<h1>Categories#show</h1> <%=@posts.each do |post| <%= post.title%> <%= post.content%> <%end%>
posts#new.html.erb
<div class="text-center"> <h1>新規投稿画面</h1> </div> <div class-"row"> <div class="col-sm-6 offset-sm-3"> <%= form_with(model: @post, local: true) do |f| %> <div class="form-group"> <%= f.label :title, 'タイトル' %> <%= f.text_field :title, class: 'form-control'%> </div> <div class="form-group"> <%= f.label :content, '内容'%> <%= f.text_area :content, class: 'form-control' %> </div> <div class="field"> <%= f.label :category_id, 'カテゴリ'%> <%= f.collection_select :category_id, Category.all, :id, :symptoms %> </div> <div class="text-center"> <%= f.submit '投稿'%> <%end%> </div> </div> </div>
routing
Rails.application.routes.draw do root to: 'toppages#index' get 'login', to: 'sessions#new' post 'login', to: 'sessions#create' delete 'logout', to: 'sessions#destroy' get 'ranking', to: 'posts#rank' resources :users, only: [:index, :show, :new, :create] resources :categories, only: [:index, :show] resources :posts, only: [:index, :show, :new, :create, :destroy, ] do resource :favorites, only: [:create, :destroy] resources :comments, only: [:create] end end
prefix
categories GET /categories(.:format) categories#index category GET /categories/:id(.:format) categories#show
_navbar.html.erb (パーシャル化してあるナビゲーションバーのcategories#indexへのリンク)
<li class="nav-item"><%= link_to 'カテゴリ', categories_path, class: 'nav-link js-scroll-trigger' %></li>
class Category < ApplicationRecord has_many :posts end
class Post < ApplicationRecord belongs_to :user has_many :comments has_many :favorites, dependent: :destroy belongs_to :category def favorited_by?(user) favorites.where(user_id: user.id).exists? end end
class CreateCategories < ActiveRecord::Migration[5.2] def change create_table :categories do |t| t.string :symptoms t.timestamps end end end
class CreatePosts < ActiveRecord::Migration[5.2] def change create_table :posts do |t| t.string :title t.string :content t.integer :user_id t.integer :category_id t.timestamps end end end