has_many:通过 - 复杂的模型

时间:2011-10-06 21:39:19

标签: ruby-on-rails-3 polymorphism has-many

我有一组非常复杂的模型,我正在试图弄清楚如何设置它以便rails将生成链式查询(尽管我不确定它是否可行)。所以我的问题最终是:如何将这些链接在一起或如何正确地对这种类型的函数进行分页?

首先,高概述。

这是一个“社交网络”,我的用户可以是studentsteachersStudentsteachers可以互相关注。两者都可以在网站上执行导致activity_items的事情。学生可以属于老师。因此,如果学生正在关注老师,他们也应该看到该老师下的activity_items名学生。

这就是复杂的地方。我想弄清楚如何显示活动源。

现在模特:

model ActivityItem < ActiveRecord::Base
  belongs_to :profile, :polymorphic => :true
  attr_accessor :posted_by_user
end

model Following < ActiveRecord::Base
  belongs_to :profile, :polymorphic => true
  belongs_to :following, :polymorphic => true
end

model Student < ActiveRecord::Base
  has_many :following_relationships, :as => :profile, :class_name => "Following"
  has_many :follower_relationships, :as => :following, :class_name => "Following"

  # getting the actual student/teacher model for each relationship
  def following
    self.following_relationships.reset
    following_relationships.collect(&:following)
  end

  def activity_feed
    all = following
    all.inject([]) do |result,profile|
      result | profile.activity_items
    end
  end

end

model Teacher < ActiveRecord::Base
  [same as student, really it is in an Extension]
end

所以我最关心的方法是activity_feed。如果不每次都运行大量查询,我不确定如何对数据进行分页。我还有一些方法可以遍历每个activity_item并将posted_by_user设置为true或false,以便让我知道它是由他们直接或间接关注的人(通过教师)创建的activity_item。

我如何修改它以便我能够

(A)获取一个(或两个或三个)查询,以便我可以对其进行分页方法。

(B)如何正确缓存/分页这样的大数据集?

0 个答案:

没有答案
相关问题