rails
1#routes.rb 2 3Rails.application.routes.draw do 4 get 'likes/index' 5 post '/likes', to: 'likes#create' 6 7 devise_for :users 8 root to: 'tweets#index' 9 namespace :tweets do 10 resources :searches, only: :index 11 end 12 resources :tweets do 13 resources :likes, only: [:create, :destroy] 14 resources :comments, only: :create 15 end 16 resources :users, only: :show 17 18end
rails
1#likes_controller 2 3class LikesController < ApplicationController 4 def index 5 @like_tweets = current_user.like_tweets 6 end 7 8 def create 9 like = Like.new #Likeクラスのインスタンスを作成 10 like.user_id = current_user.id #current_userのidを変数に代入 11 like.tweet_id = params[:tweet_id] 12 13 if like.save #likeが保存できているかどうかで条件分岐 14 redirect_to tweets_path, success: 'いいねしました' 15 else 16 redirect_to tweets_path, danger: 'いいねに失敗しました' 17 end 18 end 19 20 def destroy 21 @like = Like.find_by(user_id: current_user.id, tweet_id: params[:tweet_id]) 22 @like.destroy 23 redirect_to tweets_path, success: 'いいねを取り消しました' 24 end 25end
rails
1#_tweet.html.hml 2 <div class="content_post" style="background-image: url(<%= tweet.image %>);"> 3 <div class="more"> 4 <span><%= image_tag 'arrow_top.png' %></span> 5 <ul class="more_list"> 6 <li> 7 <%= link_to '詳細', "/tweets/#{tweet.id}", method: :get %> 8 </li> 9 <% if user_signed_in? && current_user.id == tweet.user_id %> 10 <li> 11 <%= link_to '編集', "/tweets/#{tweet.id}/edit", method: :get %> 12 </li> 13 <li> 14 <%= link_to '削除', "/tweets/#{tweet.id}", method: :delete %> 15 </li> 16 <% end %> 17 </ul> 18 </div> 19 <%= simple_format(tweet.text) %> 20 <span class="name"> 21 <a href="/users/<%= tweet.user.id %>"> 22 <span>投稿者</span><%= tweet.user.nickname %> 23 </a> 24 </span> 25 <% if user_signed_in? && current_user.likes.find_by(tweet_id: tweet.id) %> 26 <%= link_to likes_path(tweet_id: tweet.id), method: :post do %> 27 <i class="far fa-heart like-btn" ></i> 28 <% end %> 29 <% else %> 30 <%= link_to likes_path(tweet_id: tweet.id), method: :delete do %> 31 <i class="fas fa-heart unlike-btn"></i> 32 <% end %> 33 <% end %> 34 </div>
あなたの回答
tips
プレビュー