Rails由用户共享的不同项目的项目提要,后跟当前用户

时间:2013-05-11 19:01:23

标签: ruby-on-rails activerecord rails-postgresql

所以我正在尝试为项目提供不同的项目,每个项目都可以由许多用户共享。我的数据模型是:

用户:has_many:postss,has_many:products,:through => :贴子

产品has_many:postss,has_many:users,:through:postss

发布belongs_to:user,belongs_to:product

所以我试图找到一个可窗口(偏移,限制)的唯一产品列表,并且还获取用户数据(或至少一个字段),这样我就不必在视图中查询它。这是我现在正在运行的查询:

 def feed_items(offset, limit)
  ids = followed_users.map(&:id)
  ids.push id
  all_rows_sql = Posting.where("user_id IN (#{ids.join(',')})").order("created_at DESC").select("product_id, row_number() over (partition by product_id) as row_number").to_sql
  sql = "SELECT product_id FROM(#{all_rows_sql}) as rows where row_number = 1 OFFSET #{offset} LIMIT #{limit}"
  postings = ActiveRecord::Base.connection.execute(sql)
  product_ids = []
  postings.each {|p| product_ids.push p['product_id'].to_i}
  products = Product.find product_ids
  orderedProducts = []
  for product in products
    orderedProducts[product_ids.index(product.id)] = product
  end
  orderedProducts
end

这会在合理的时间内获取产品列表,但在我看来,我必须说product.users.each来显示项目下方的用户列表。这导致大量查询,并且还从视图中命中数据库,这两者都是一个问题。有没有人知道如何在产品ID的同时获取用户ID?

由于

0 个答案:

没有答案