Ruby on rails Rails应用程序中tweets请求的优化

Ruby on rails Rails应用程序中tweets请求的优化,ruby-on-rails,Ruby On Rails,在我的Rails应用程序中,我想列出用户发布的所有推文,然后是当前用户(与登录twitter时看到的相同) 目前我有以下声明: @tweets = Tweet.includes(:user).where(user_id: current_user.followed.pluck(:id)) 它工作得很好,但从性能的角度来看,我认为它很糟糕 你能告诉我,在我的情况下,什么是最有效的查询 更新:我有三种型号: class User < ActiveRecord::Base has_ma

在我的Rails应用程序中,我想列出用户发布的所有推文,然后是当前用户(与登录twitter时看到的相同)

目前我有以下声明:

@tweets = Tweet.includes(:user).where(user_id: current_user.followed.pluck(:id))
它工作得很好,但从性能的角度来看,我认为它很糟糕

你能告诉我,在我的情况下,什么是最有效的查询

更新:我有三种型号:

class User < ActiveRecord::Base
    has_many :tweets, dependent: :destroy
    has_many :followerships, class_name: 'Followership', foreign_key: 'followed_id'
    has_many :followedships, class_name: 'Followership', foreign_key: 'follower_id'
    has_many :followers, through: :followerships, source: :follower
    has_many :followed, through: :followedships, source: :followed
end

class Followership < 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

class Tweet < ActiveRecord::Base
  belongs_to :user
end

您是否认为这是一个性能问题?从表面上看,这看起来像是一个微优化。我认为这段代码将生成一个(Rails非常聪明,可以构建子查询)或两个查询。它应该工作得相当快。您可以尝试
EXPLAIN
查询,看看它是否可以加速(可能添加一些索引)。查看模型和关联会很有用。只要模型关联正确,这应该是一个查询。谢谢您的评论。我运行了
explain
,结果发现我有3个查询。这个模型有问题吗?
   (0.2ms)  SELECT "users"."id" FROM "users" INNER JOIN "followerships" ON "users"."id" = "followerships".    "followed_id" WHERE "followerships"."follower_id" = ?  [["follower_id", 4]]
  Tweet Load (0.3ms)  SELECT "tweets".* FROM "tweets" WHERE "tweets"."user_id" IN (2, 3, 5, 7, 8, 9, 10, 13,     14, 15)
  User Load (0.4ms)  SELECT "users".* FROM "users" WHERE "users"."id" IN (2, 3, 5, 7, 8, 9, 13, 14, 15)
 => EXPLAIN for: SELECT "tweets".* FROM "tweets"  WHERE "tweets"."user_id" IN (2, 3, 5, 7, 8, 9, 10, 13, 14, 15)
0|0|0|SEARCH TABLE tweets USING INDEX index_tweets_on_user_id (user_id=?)
0|0|0|EXECUTE LIST SUBQUERY 1

EXPLAIN for: SELECT "users".* FROM "users"  WHERE "users"."id" IN (2, 3, 5, 7, 8, 9, 13, 14, 15)
0|0|0|SEARCH TABLE users USING INTEGER PRIMARY KEY (rowid=?)
0|0|0|EXECUTE LIST SUBQUERY 1