Ruby on rails RubyonRails使用过滤器值数组进行优化搜索?
我有一个具体的例子,但一般的问题是:当您有一个要匹配的筛选值数组时,检索记录的最佳方式是什么 假设我有Ruby on rails RubyonRails使用过滤器值数组进行优化搜索?,ruby-on-rails,arrays,ruby,activerecord,Ruby On Rails,Arrays,Ruby,Activerecord,我有一个具体的例子,但一般的问题是:当您有一个要匹配的筛选值数组时,检索记录的最佳方式是什么 假设我有User和Post记录,其中User有许多:Post 我有一个关系模型,看起来像这样: class Relationship < ActiveRecord::Base belongs_to :follower, class_name: "User" belongs_to :followed, class_name: "User" validates :follower_id,
User
和Post
记录,其中User有许多:Post
我有一个关系
模型,看起来像这样:
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
我认为有一种更好的方法可以使用活动记录函数实现这一点,但我不知道如何使它们与数组一起工作。例如,如果我编译一个Userid
值数组,而不是完整的模型,并尝试运行此代码以获取post数组:
posts = Post.where(
user_id: user_ids
).order('created_at DESC').limit(21)
它返回一个空数组。有没有比我当前的解决方案更好的方法来使用筛选值数组进行搜索
更新:附加模态代码:
class Post < ActiveRecord::Base
belongs_to :user
...
class Post
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
...
class用户
您使用用户ID的想法很好。如果该查询返回一个空数组,那么您是否检查以确保用户ID是您期望的
至于代码,您需要仔细研究和修改。它们是内置的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)
注释:由于CeReDATA AT应该遵循ID创建顺序,所以我会考虑基于ID而不是CREATEDATION,因为它应该有索引。
有一个<代码>用户< /代码>代码> HasyMul众多:如下,如下:跟随者,类名字:‘关系’< /代码>?是的,当我在ActurReCordD集合上迭代时,我用更多的模态代码更新了,使用find_each
而不是each
find_each
批量加载集合中的记录,而不是一次加载所有记录,这显然对内存加载更安全。
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.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)