问题
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