フォロー機能を実装する中、フォローするが上手くいきません。
Modelで、def follow(user)内のuser.idの値が取得できずに困っています。
Error
1undefined method `id' for nil:NilClass
Ruby
1<% if @current_user != @user %> 2 <% if @current_user.following?(@user) %> 3 <%= button_to "フォロー中", friendship_path(user_id: @user_id), method: :delete, :class => "btn" %> 4 <% else %> 5 <%= button_to "フォローする", friendships_path(user_id: @user_id), method: :post, :class => "btn" %> 6 <% end %> 7<% end %>
Controller
1class FriendshipsController < ApplicationController 2 before_action :authenticate_user 3 before_action :find_user 4 5 def create 6 @current_user.follow(@user) 7 redirect_back(fallback_location: "something") 8 end 9 def destroy 10 @current_user.unfollow(@user) 11 redirect_back(fallback_location: "something") 12 end 13 def find_user 14 @user = User.find_by(id: params[:id]) 15 end 16end
Model
1 has_many :active_friendships, class_name:"Friendship", foreign_key: "follower_id", dependent: :destroy 2 has_many :passive_friendships, class_name:"Friendship", foreign_key: "followed_id", dependent: :destroy 3 has_many :following, through: :active_friendships, source: :followed 4 has_many :followers, through: :passive_friendships, source: :follower 5 6 def follow(user) 7 active_friendships.create(followed_id: user.id) 8 end 9 10 def unfollow(user) 11 active_friendships.find_by(followed_id: user.id).destroy 12 end 13 14 def following?(user) 15 following.include?(user) 16 end
user.idの値が取得できないのですが、unfollow時には正しく取得できます。
また、active_friendships.create(followed_id: 1)
のように直でvalueを入れた場合には正しくuser.id:1へのフォローが正常に機能します。
ご協力お願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/11/23 12:19 編集
2018/11/23 17:52 編集
2018/11/24 03:47
2018/11/24 03:49