Search code examples
ruby-on-railsruby-on-rails-3activerecordactivemodel

Rails, how to query a friendship model when there are two equal fields: user_id & friend_id?


I have a friendship model like so:

Friendship (user_id, friend_id, status)

Where there is only 1 record to establish a friendship between User A and User B. user_id is the user who initiated on friend_id. On create the status is "pending." When the friend_id approves or ignores, that status is updated.

Give the relationship. How can I get all of a user's contacts? The query needs to query across both user_id and friend_id, which is why @user.friendships does not work. That only shows the friends that the created.

Ideas?


Solution

  • I built a rails app that needs to maintain a genealogy of relationships between people. What I did was create the equal and opposite map for each and every relationship, e.g. [a, b, father], [b, a, son] using the after_create, after_update and after_destroy triggers. The reason I did this was I wanted very fast search from person to person. Works great.

    The create code looks like this:

    def after_create(record)
      if ! record.relative.has_relative(record.person_id)
        new_relationship = Relationship.new(:relative => record.person, 
          :relationship => hantai(record.relative.gender, record.person.gender, record.relationship))
        record.relative.relationships << new_relationship
        record.relative.save
      end
     end
    

    Where the Relationship object is the same as your Friendship object and the record in this case is the person.