0

我有自我参照协会工作。我的问题是在用户/节目上,我想根据用户与当前用户的关系显示不同的文本。

目前,如果用户 = 当前用户,我将其设置为不显示任何内容。如果用户不是当前用户并且不是当前用户的朋友,我想显示一个链接来关注用户。最后,如果用户不是当前用户并且已经是当前用户的朋友,我想显示文本说“朋友”。

友谊.rb

belongs_to :user
belongs_to :friend, :class_name => "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 %>
4

1 回答 1

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 %>
于 2013-02-14T15:32:44.680 回答