2016-06-22 64 views
0

在ruby中,我試圖阻止用戶添加某人作爲朋友,如果他們中的任何一個在他們的忽略列表上有其他人。在友誼控制器,我試圖定義紅寶石,before_action混淆

class FriendshipsController < ApplicationController 
before_action :ignored_user, only: :create 

而且

def ignored_user 
    if current_user.foes.include?(@user) 
    flash[:notice] = "Unable to send friend request." 
    redirect_to :back 
    end 
end 

在此背景下,CURRENT_USER是誰在登錄的用戶,@user是其配置文件正在觀看的用戶,敵人意味着「無論是他們選擇忽視的人,還是忽視他們的人。」所有這些似乎工作,除了「如果current_user等等等等線」。如果我將它替換爲「if current_user.admin?」那麼它的工作原理與您所期望的完全相同如果該用戶是管理員,則他們無法發送任何朋友請求。如果我用「if current_user.id == 2」替換它,它也可以像你期望的那樣工作。我試着上面的代碼的很多很多的變化,包括像更換髮生故障的線路:

if Disagreement.where(foe_id: [@user, params[:id]], user_id: [current_user, params[:id]]).first 

其中工程別處,剛纔不是在友誼控制器。

至於錯誤消息:沒有。我的嘗試總是以朋友添加時不應該結束的方式結束,或者所有的朋友請求都被阻止,包括朋友對不是的用戶請求被忽略。任何幫助,這將不勝感激。

+1

你在哪裏給'@ user'賦值?我的猜測是'@ user'是'nil','current_user.foes.include?(nil)'總是'false'。爲了解決這些問題,您可以添加'puts「@user:#{@ user}」'並檢查控制檯中的服務器輸出以查看正在發生的事情。 –

+1

更好的是,告訴我們'current_user','current_user.foes'和'@ user'的價值。提示:而不是'如果foo.bar.first'做了'if foo.bar.exists?'而不是在這種情況下實例化'Disagreement',它將返回true或false。 – Leito

+0

哎呀,atuser(stackoverflow不讓我發表這個答覆,除非我寫「atuser」)在users_controller中定義在顯示操作(和其他一些)下。你是對的!添加後,控制檯輸出「atuser is:」。我嘗試用「User.find(params [:id])」代替atuser,但是返回這個錯誤:FriendshipsController中的ActiveRecord :: RecordNotFound#create 找不到用戶'id'= raise RecordNotFound,使用'#{primary_key}'=#{id}找不到#{name}「 在第37行,即」if current_user etc.「線。 – Display

回答

0

一個比我更聰明的人給了我解決方案。我完全刪除了「before_action:ignored_user,只有::創建」部分,以及「def ignored_user」部分。所有這一切都已經被替換爲:

class FriendshipsController < ApplicationController 

    def create 
    @user = User.find(params[:friend_id]) 
    if current_user.foes.include?(@user) 
     flash[:notice] = "Unable to send friend request. You are ignoring this user or vice versa." 
     redirect_to :back 
     puts "@user is: #{@user}" #This line only existed for the sake of figuring out the problem 
     puts "@user.id is: #{@user.id}" #Same 
     puts "current_user.foes are: #{current_user.foes}" #Same 
    else 
     @friendship = current_user.friendships.build(friend_id: params[:friend_id]) 
     if @friendship.save 
     flash[:notice] = "Friend request sent!" 
     redirect_to :back 
     end 
    end 
    end 

的問題是,在任何的它的通常定義的方式友誼控制器無法識別@user,由於PARAMS [:ID]部分。因爲這是重寫用於友誼控制器,控制器假定通過「id」,你的意思是一些友誼的id,而不是用戶的id。給我解決方案的人意識到,你可以用「:friend_id」替換「:id」,因爲在這個動作的上下文中,這兩個ID總是同義的,因爲你總是從他們自己的人中添加人個人資料頁。所以我從來沒有想過如何直接從一個不同的控制器中引用用戶的ID,但我已經學會了下一個最好的東西。