2013-02-14 82 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 %>