我創建了一個與用戶(設計)完全相同的以下系統。 我跟着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
謝謝您的幫助
你可以做'current_user.friendships.where(friend_id:params [:friend_id])。any?'來檢查用戶是否是你的朋友。 –
@JagjotSingh你好Jagjot我把這個代碼?在我的控制器? –
在創建操作中的構建語句之前,您的控制器中可以。如果用戶已經是朋友,您也可以在視圖中使用相同的方式顯示其他鏈接。 –