How to restrict a view by

限于喜欢 提交于 2019-12-11 14:49:29

问题


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 visiting a user/show page of a user that the current_user is already friends with...what is the syntax for checking the Friendships table for an existing friendship.

Here is 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:


I'd go with something like this:

def friends_with?(other_user)
  friends.include?(other_user) || inverse_friends.include?(other_user)
end


来源:https://stackoverflow.com/questions/4242082/how-to-restrict-a-view-by

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