public
Created

friendships

  • Download Gist
friendships_controller.rb
Ruby
1 2 3 4
@friends_out = Friendship.where(:user_id=>current_user.id) #users "i" want to be friends with
@friends_in = Friendship.where(:friend_id=>current_user.id) #users who want to be friend with "me"
# users who haven't added "my" id to Friendship and vice versa
# user who are my friend and i'm their friends.

Assuming you are using a SQL DB, you could do:

#In your user model:
has_and_belongs_to_many :fields
has_and_belongs_to_many :friends, :class_name => "User",
:foreign_key => "other_user_id"

#in your controller
@friends = UsersUser.where(:status=>friend && :user_id => current_user.id)
@friends_out = UsersUser.where(:status=>pending && :other_user_id => current_user.id)
@friends_in = UsersUser.where(:status=>pending && :user_id => current_user.id)

So in this example if you wanted to be a friend with me, your id would be the other_user_id and mine would be user_id and the status could be set to pending, if I accept you could change the status to accepted or however you would like.

Also if @user is equal to the current logged in user, in your view you could just call @user.friends to get all of your friends regardless of status.

the UsersUser model you have there is similar to the Friendship model in

http://railscasts.com/episodes/163-self-referential-association

You way adds a status, so you just need to accept those who have added you.

I understand what you are doing now with status, is saves the cross referencial query.

thanks.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.