开发者

Advanced friendship model and queries in Rails 3

I have friendship model, and for every new friendship, I create two new records:

  • User1 and Friend1
  • Friend1 and User1

I can retrieve all standard staffs like: friends, friendships, pending_friends... The situation becomes complicated when I try to get common friends, friends of friends...

For now to get common friendships, I use something like:

has_many :common_friendships, :class_name => 'Friendship', :conditions=>'friendships.user_id = #{self.id}' do
  def common_with(friend)
    joins("inner join friendships fl2 on friendships.friend_id = fl2.user_id").where("fl2.friend_id = #{friend.id}")
  end
end 

Also I can use full query with finder_sql like:

select distinct *
from friendships fl1
inner join friendships fl2 on fl开发者_开发问答1.friend_id = fl2.user_id
where fl1.user_id = 1  and fl2.friend_id = 2

How can I do that in an elegant way in Rails 3?


Check out the answer on this question:

How to Implement a Friendship Model in Rails 3 for a Social Networking Application?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜