ユーザーが投稿したマイクロポストに対してコメントを投稿することはできるのですが、削除ができないので、できるようにしたいです。
views/microposts/show.html.erb
<h2>コメント一覧</h2> <% @micropost.comments.each do |c| %> <div> <%= c.body %> <% if current_user?(micropost.user) %> <%= link_to "削除するdelete", micropost, method: :delete, data: { confirm: "本当に削除しますか?You sure?" } %> <% end %> </div> <% end %>
controllers/microposts_controller.rb
class MicropostsController < ApplicationController before_action :logged_in_user, only: [:create, :destroy] before_action :correct_user, only: :destroy def show @micropost = Micropost.find(params[:id]) @comment = @micropost.comments.new @comments = @micropost.comments end def create @micropost = current_user.microposts.build(micropost_params) if @micropost.save flash[:success] = "Micropost created!" redirect_to root_url else @feed_items = [] render 'static_pages/home' end end def destroy @micropost.destroy flash[:success] = "Micropost deleted" redirect_to request.referrer || root_url end private def micropost_params params.require(:micropost).permit(:content, :picture) end def correct_user @micropost = current_user.microposts.find_by(id: params[:id]) redirect_to root_url if @micropost.nil? end end
controllers/comments_controller.rb
class CommentsController < ApplicationController def create @micropost = Micropost.find(params[:micropost_id]) @comment = @micropost.comments.new(comment_params) @comment.user_id = current_user.id if @comment.save # redirect_back(fallback_location: micropost_url(micropost.id)) # redirect_back(fallback_location: root_path) redirect_to [@micropost] else flash[:success] = "コメントできませんでした" redirect_back(fallback_location: root_path) end end def destroy # @comment = Comment.find_by(id: params[:id]) @comment = current_user.comments.find(params[:id]) @comment.destroy redirect_to request.referrer || root_url end private def comment_params params.require(:comment).permit(:body) end end
config/routes.rb
Rails.application.routes.draw do get 'password_resets/new' get 'password_resets/edit' get 'sessions/new' root 'static_pages#home' get '/help', to: 'static_pages#help' get '/about', to: 'static_pages#about' get '/contact', to: 'static_pages#contact' get '/signup', to: 'users#new' post '/signup', to: 'users#create' get '/login', to: 'sessions#new' post '/login', to: 'sessions#create' delete '/logout', to: 'sessions#destroy' resources :users do member do get :following, :followers end end resources :users resources :account_activations, only: [:edit] resources :password_resets, only: [:new, :create, :edit, :update] resources :microposts, only: [:create, :destroy, :show] do resources :comments, only: [:create, :destroy, :show] end resources :relationships, only: [:create, :destroy] end
あなたの回答
tips
プレビュー