jim
jim

Reputation: 9138

Rails, how to do a custom active record join that doesn't use ID

I have two models Users and Friendships in my RoR application

The friendships table contains two integer fields user1 and user2, both these fields represent a relationship.

How would I go about selecting all friends for a given user id that exists in either the user1 or user2 field?

Thanks.

Upvotes: 1

Views: 674

Answers (3)

nyaa
nyaa

Reputation: 1736

class User
  def friends
    user_ids = Friendship.where(["user1 = :id OR user2 = :id", :id => self.id]).inject([]) {|sum,x| sum << x.user1 && sum << x.user2 }.uniq-[self.id]
    User.find(user_ids)
  end
end

Upvotes: 1

tycooon
tycooon

Reputation: 508

Take a look at ActiveRecord's has_many method documentation. I think you may be able to do something like:

class User
  has_many :friendships, :finder_sql => lambda { |user| ["SELECT * FROM friendships WHERE user1 = :id OR user2 = :id", :id => user.id] }

  def friends
    ids = friendships.map(&:user1) + friendships.map(&:user2)
    ids.uniq!
    ids.delete(id)
    User.find(ids)
  end
end

Upvotes: 1

Jakub Oboza
Jakub Oboza

Reputation: 5421

You can use find_by_sql

http://apidock.com/rails/ActiveRecord/Base/find_by_sql/class

Upvotes: 2

Related Questions