2016-03-27 24 views
0

我創建了一個與用戶(設計)完全相同的以下系統。 我跟着Ryan Bates Rails演員陣容http://railscasts.com/episodes/163-self-referential-association驗證唯一性方法僅遵循一次

在這段代碼中我們可以添加很多次相同的用戶,我想阻止人們添加爲朋友的時間。

例如,當User1添加了User2時,鏈接將被阻止。 我給你一些代碼來理解。

遷移被稱爲友誼之品

class CreateFriendships < ActiveRecord::Migration 
    def change 
    create_table :friendships do |t| 
     t.integer :user_id 
     t.integer :friend_id 

     t.timestamps null: false 
    end 
    end 
end 

爲用戶的模型是

has_many :friendships 
has_many :friends, :through => :friendships 

作爲朋友的模型是

belongs_to :user 
belongs_to :friend, :class_name => "User" 

友誼控制器

class FriendshipsController < ApplicationController 
    def create 
    @friendship = current_user.friendships.build(:friend_id => params[:friend_id]) 
    if @friendship.save 
     flash[:notice] = "Added friend." 
     redirect_to current_user 
    else 
     flash[:error] = "Unable to add friend." 
     redirect_to current_user 
    end 
    end 

def destroy 
    @friendship = current_user.friendships.find(params[:id]) 
    @friendship.destroy 
    flash[:notice] = "Removed friendship." 
    redirect_to current_user 
    end 
end 

謝謝您的幫助

+0

你可以做'current_user.friendships.where(friend_id:params [:friend_id])。any?'來檢查用戶是否是你的朋友。 –

+0

@JagjotSingh你好Jagjot我把這個代碼?在我的控制器? –

+0

在創建操作中的構建語句之前,您的控制器中可以。如果用戶已經是朋友,您也可以在視圖中使用相同的方式顯示其他鏈接。 –

回答

1

你可以做這樣的事情在你的控制器:

... 
def create 
    if current_user.friendships.where(friend_id: params[:friend_id]).any? 
    flash[:error] = "You already have added this user." 
    redirect_to current_user 
    else 
    @friendship = current_user.friendships.build(:friend_id => params[:friend_id]) 
    if @friendship.save 
     flash[:notice] = "Added friend." 
     redirect_to current_user 
    else 
     flash[:error] = "Unable to add friend." 
     redirect_to current_user 
    end 
    end 
end 
... 

而且在你的意見,你可以做這樣的事情:

... 
if current_user.id == user.id 
    link_to 'Your Profile', '#!' 
elsif current_user.friendships.where(friend_id: user.id).any? 
    link_to 'Friends', '#!' 
else 
    link_to 'Add Friend', path_here 
end 
... 
+0

它的作品謝謝! –

+0

太棒了!樂於幫助。 –

+0

:)我有最後一個問題。並阻止你的自動跟蹤,因爲我可以添加自己作爲朋友。你有想法做到這一點嗎? –