2013-02-14 83 views
0

我有自我指涉關聯工作。我的問題是,在users/show上,我想根據用戶與當前用戶的關係顯示不同的文本。Follow Model的條件鏈接

目前,如果用戶=當前用戶,我將它設置爲不顯示任何內容。如果用戶不是當前用戶,並且不是當前用戶的朋友,我想顯示一個鏈接以跟隨用戶。最後,如果用戶不是當前用戶,並且已經是當前用戶的朋友,我想顯示文本以說「朋友」。

friendship.rb

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

user.rb

has_many :friendships 
has_many :friends, :through => :friendships 
has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id" 
has_many :inverse_friends, :through => :inverse_friendships, :source => :user 

用戶/顯示

<% unless @user == current_user %> 
    <%= link_to "Follow", friendships_path(:friend_id => @user), :method => :post %> 
<% end %> 

回答

1

首先我將定義上,我們可以用它來確定用戶模型的方法如果用戶是另一個用戶的朋友。這將是這個樣子:

class User < ActiveRecord::Base 
    def friends_with?(other_user) 
    # Get the list of a user's friends and check if any of them have the same ID 
    # as the passed in user. This will return true or false depending. 
    friends.where(id: other_user.id).any? 
    end 
end 

然後我們可以使用視圖來檢查當前用戶是朋友與給定用戶:

<% unless @user == current_user %> 
    <% if current_user.friends_with?(@user) %> 
    <span>Friends</span> 
    <% else %> 
    <%= link_to "Follow", friendships_path(:friend_id => @user), :method => :post %> 
    <% end %> 
<% end %>