How do I reference my Friendships table to conditionally display code?

你说的曾经没有我的故事 提交于 2020-01-06 05:39:05

问题


I have successfully set up a friendship self referencial association for users in my Ruby on Rails app after following Ryan Bates' railscast. I can successfully follow, unfollow, and view who is following. Now I want to pull in another element and I am not sure how to do it.

When on my current_user dashboard page I want to conditionally display an element based on whether or not the current_user is following anyone and if the current_user is being followed by anyone. In oother words, if the current_user is not following anyone I don't want to display the following:

<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 # -->

And if the current_user is not being followed by anyone I don't want to display this:

<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 # -->

These are how the associations are set up:

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:


You can check if there are any friends or inversed_friends with the method any? It will return true if there are one or more records associated, otherwise it will be false

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

And you can do the exact same thing with inverse_friends

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


来源:https://stackoverflow.com/questions/4242170/how-do-i-reference-my-friendships-table-to-conditionally-display-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!