如何引用我的友谊表以有条件地显示代码?

时间:2010-11-22 04:01:12

标签: ruby-on-rails ruby associations

Ryan Bates' railscast之后,我已经成功地在我的Ruby on Rails应用中为用户建立了友情自我参与协会。我可以成功地关注,取消关注,并查看谁在关注。现在我想引入另一个元素,我不知道该怎么做。

在我的current_user仪表板页面上,我想根据current_user是否跟随任何人以及是否有任何人关注current_user来有条件地显示元素。换句话说,如果current_user没有跟随任何人,我不想显示以下内容:

<div id="following" class="">
 <h2 class="tk-john-doe">Following</h2>
 <% for friendship in @user.friendships %>
  <div class="friend">
   <%= link_to (friendship.friend.username), friendship.friend %> <%= link_to "(Unfollow)", friendship, :method => :delete, :class => "unfollow" %>
   </div> <!-- close # -->
 <% end %>
</div> <!-- close # -->

如果没有人关注current_user,我不想显示:

<div id="following-you" class="grid_4 alpha">
  <h2 class="tk-john-doe">Followers</h2>
  <% for user in @user.inverse_friends %>
    <div class="friend">
      <%= link_to (user.username), user %>
    </div> <!-- close # -->
  <% end %>
 </div> <!-- close # -->

这些是如何建立关联的:

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

  def friends_workouts
    @friends_workouts ||= Workout.find_all_by_user_id(self.friends.map(&:id), :order => "created_at DESC", :limit => 3)
  end

1 个答案:

答案 0 :(得分:0)

您可以使用方法检查是否有朋友或inversed_friends? 如果有一个或多个记录关联,它将返回true,否则将为false

<% if @user.friends.any? %>
<div id="following" class="">
<!-- content -->
</div>
<% end %>

你可以用inverse_friends完成同样的事情

<% if @user.inverse_friends.any? %>