Twitterのような投稿に、コメントを付けようと考えています。
要は以下の写真のような感じです。
https://gyazo.com/5e6658669f1e8f0b7b8e03207e88a1ba
コメントしたら、トップページに戻るルートを希望しています。
そこで、試しに投稿した所、ルーティングエラーが発生しました。
https://gyazo.com/b20681ffcc8460fa71f3da47e87bdb2a
現在のコードは以下の通りです。
config/routes.rb
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
comments_controller.rbのcreate部分
class CommentsController < ApplicationController before_action :set_comment, only: [: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_back(fallback_location: root_path) else render 'toppages/index' end end 以下省略
viewは以下のとおりです。
<ul class="media-list"> <% posts.each do |post| %> <% user = post.user %> <li class="media"> <div class="media-left"> <img class="media-object img-rounded" src="<%= gravatar_url(user, options = { size: 50 }) %>" alt=""> </div> <div class="media-body"> <div> <%= link_to user.name, user_path(user) %> <span class="text-muted">posted at <%= post.created_at %></span> </div> <div> <p><%= image_tag post.picture,:size =>"280x210" %></p> <p><%= post.content %></p> <% if @comments %> <% @comments.each do |comment| %> <div class="name2">投稿者:<%= link_to comment.user.username, "/users/#{comment.user_id}" %> 投稿日時:<%= comment.created_at.strftime("%Y-%m-%d %H:%M:%S") %></div> <div class="name2"><%= comment.text %></div> <% end %> <% end %> <br/> <% if current_user %> <%= form_tag("/posts/#{@post.id}/comments", method: :post) do %> <textarea cols="30" name="text" placeholder="コメントする" rows="2"></textarea> <br/> <input type="submit" value="コメントの投稿"> <% end %> <% end %> </div> <br/> <div> <% if current_user == post.user %> <%= link_to "削除", post, method: :delete, data: { confirm: "本当に削除してよろしいですか?" }, class: 'btn btn-danger btn-sm' %> <% end %> </div> </div> </li> <% end %> <%= paginate posts %> </ul>
色々と試してみましたが、中々解決できませんでした。
解決方法をご教示していただけますでしょうか?