Ruby on Rails使用filter值数组进行最佳搜索?

我有一个具体的例子,但一般的问题是:当你有一个匹配的过滤值数组时,什么是检索记录的最佳方法?

假设我有UserPost记录,其中User has_many :posts

我有一个看起来像这样的Relationship模型:

 class Relationship < ActiveRecord::Base belongs_to :follower, class_name: "User" belongs_to :followed, class_name: "User" validates :follower_id, presence: true validates :followed_id, presence: true end 

我想编写一个函数,返回以下关注时间顺序的post – 也就是说,您关注的用户所关注的所有post都在关注,不包括您关注的任何人的重复和post。

我的解决方案是首先编译所有感兴趣的用户的数组:

 users = [] @user.following.each do |f| f.following.each do |ff| users << ff end end # dedupe users = users.uniq #remove self and following users.delete(@user) @user.following.each do |f| users.delete(f) end 

然后编译他们的post并订购它们:

 posts = [] users.each do |u| posts += u.posts end posts.sort_by!{|x| x[:created_at]}.reverse! 

我认为使用Active Record函数有更好的方法,但我无法弄清楚如何使它们与数组一起工作。 例如,如果我编译一个User id值而不是完整模型的数组,并尝试运行此代码来获取post数组:

 posts = Post.where( user_id: user_ids ).order('created_at DESC').limit(21) 

它返回一个空数组。 有没有比我当前的解决方案更好的方法来搜索filter值数组?

更新:附加模态代码:

 class Post < ActiveRecord::Base belongs_to :user ... 

User.rb

 class User < ActiveRecord::Base has_many :photos has_many :active_relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy has_many :passive_relationships, class_name: "Relationship", foreign_key: "followed_id", dependent: :destroy has_many :following, through: :active_relationships, source: :followed has_many :followers, through: :passive_relationships, source: :follower ... 

您使用user_ids的想法很好。 如果该查询返回一个空数组,那么您是否检查过以确保user_ids是您所期望的那个?

至于代码,你需要查看Enumerable #map和#flat_map 。 它们是内置的ruby方法,用于完成您尝试使用#each循环所做的事情。 您的代码可能会减少到:

 user_ids = user.followings.flat_map { |following| following.following_id } user_ids.uniq! user_ids -= [user.id, user.following_ids].flatten Post.where(user_id: user_ids).order(id: :desc).limit(21) 

注意:由于created_at应该遵循id创建顺序,我会考虑基于id而不是created_at进行搜索,因为它应该有一个索引。