当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails - Joining friends to other models

问题描述:

I'm still having trouble building complex joins in ActiveRecord.

I have a User model that is using the HasManyFriends plugin by Steve Ehrenberg (http://dnite.org).

Then I have a UserFeedEvent model that links users to a FeedEvent model.

What I'd like to achieve is to find all the FeedEvents linked to the friends of a User.

How should I write my ActiveRecord query?

Here are my models:

class User < ActiveRecord::Base

has_many_friends

has_many :feed_events, :through => :user_feed_events, :dependent => :destroy

has_many :user_feed_events, :dependent => :destroy

end

class UserFeedEvent < ActiveRecord::Base

belongs_to :feed_event, :dependent => :destroy

belongs_to :user

end

class FeedEvent < ActiveRecord::Base

has_many :user_feed_events, :dependent => :destroy

has_many :users, :through => :user_feed_events

serialize :data

end

Thanks in advance!

Augusto

网友答案:

Digging through HasManyFriends source leads me to believe that the following should work (or be half-way through):

EDIT: found out that source cannot point to another :has_many :through association. So you could try the updated version.

class User < ActiveRecord::Base
  #...
  has_many :user_feed_events_of_friends_by_me, :through => :friends_by_me,
    :source => :user_feed_events
  has_many :feed_events_of_friends_by_me, :through => :user_feed_events_by_me

  has_many :user_feed_events_of_friends_for_me, :through => :friends_for_me,
    :source => :user_feed_events
  has_many :feed_events_of_friends_for_me, :through => :user_feed_events_for_me

  # A wrapper to return full list of two-way friendship events
  def feeds_events_of_my_friends
    self.feed_events_of_friends_by_me + self.feed_events_of_friends_for_me
  end
end

Unfortunately the HMF plugin has two one-way friendship links, which means full list requires 2 DB queries.

网友答案:

I found a working and more traditional SQL solution:

friends_id = current_user.friends.collect {|f| f.id}.join(",")

sql = "SELECT feed_events.*, user_feed_events.user_id  FROM feed_events LEFT JOIN user_feed_events ON feed_events.id = user_feed_events.feed_event_id WHERE user_feed_events.user_id IN (#{friends_id}) GROUP BY feed_events.id ORDER BY feed_events.created_at DESC"

friend_feed_events = FeedEvent.paginate_by_sql(sql, :page => params[:page], :per_page => 30)

If you have a more efficient / more elegant way of doing the same, please let me know!

分享给朋友:
您可能感兴趣的文章:
随机阅读: