現在、UrlGenerationError in Toppages#indexが発生しています。
詳しく書くと、「No route matches {:action=>"create", :controller=>"comments", :post_id=>nil} missing required keys: [:post_id]」
です。
恐らく、postのidが渡っていないためエラーが起きていると考えられます。
現在のコードは以下の通りです。
ビュー部分
<% if current_user %> <%= form_tag(post_comments_path(@post.id), method: :post) do %> <textarea cols="30" name="text" placeholder="コメントする" rows="2"></textarea> <br/> <input type="submit" value="コメントの投稿"> <% end %> <% end %>
コメントコントローラー
class CommentsController < ApplicationController before_action :set_comment, only: [:new,:create, :destroy] before_action :require_user_logged_in def create @post = Post.find(params[:post_id]) @comment = @post.comments.new(comment_params) @comment.user_id = current_user.id #@comment = current_user.posts.comments.build(comment_params) #@comment = Comment.create(text: comment_params[:text], post_id: comment_params[:post_id], user_id: current_user.id) if @comment.save flash[:success] = "コメントしました。" #redirect_to "/posts/#{@comment.post.id}" #redirect_to post_comments_path(@post.id) #redirect_to :action =>"new" redirect_back(fallback_location: root_path) else render 'toppages/index' end end def destroy @comment.destroy flash[:success] = 'コメントを削除しました。' redirect_back(fallback_location: root_path) end private # Use callbacks to share common setup or constraints between actions. def set_comment @post = Post.find(params[:post_id]) @comment = @post.comments.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def comment_params params.require(:comment).permit(:user_id, :post_id, :content) end end
ルーティング
Rails.application.routes.draw do root to: 'toppages#index' get 'login', to: 'sessions#new' post 'login', to: 'sessions#create' delete 'logout', to: 'sessions#destroy' resources :users do member do get :followings get :followers end collection do get :search end end resources :posts, only: [:create, :destroy, :show] , shallow: true do resources :comments, only: [:create, :destroy] end resources :relationships, only: [:create, :destroy] get 'signup', to: 'users#new' end
トップページのcontroller
class ToppagesController < ApplicationController def index if logged_in? @user = current_user @post = current_user.posts.build # form_for 用 @posts = current_user.feed_posts.order('created_at DESC').page(params[:page]) end end end
ビュー部分を、<%= link_to "コメントを投稿", method: :post, :action =>"create", :controller =>"comments", :post_id =>nil, class: 'btn btn-danger btn-sm' %>
や、<%= form_tag(post_comments_path(@post.id), :action =>"create", :controller =>"comments", :post_id =>nil, method: :post) do %>
としてみたり、コントローラーのコメントアウト部分を一時有効にしてみたり、ググったりしてみましたが、中々解決できませんでした。
どなたかわかる方、ご教示お願い申し上げます。
