【问题标题】:Rails 5.2 ActiveRecord Query: Difference Between .joins and .includeRails 5.2 ActiveRecord 查询:.joins 和 .include 之间的区别
【发布时间】:2020-12-20 02:35:48
【问题描述】:

我正在为这个新项目学习 Rails 5.2(和 MySQL),我想进一步了解 join 和 includes 之间的区别。

假设项目有一个Like 模型:

<Like emoji_type user_id>

这是User 模型:

<User id username banned>

假设我只想查找未被禁止的用户 (status != 0) 的赞,并将它们按 emoji_type 分组。

这是不过滤被禁止用户的旧查询,它使用includes:

@likes_map = likes.where.not(emoji_type: nil)
  .includes(:user)
  .group_by(&:emoji_type)

这是我目前的查询(有效),它使用joins:

@likes_map = likes.joins(:user).select(:emoji_type, :username, :status)
  .where("emoji_type IS NOT NULL")
  .where("status != 0")
  .group_by(&:emoji_type)

当我尝试将内容记录到控制台时,我注意到includes 与joins 返回的结果类型存在一些差异:

# includes
p @likes.username => nil
p @likes.user.name => username

# joins
p @likes.username => username
p @likes.user.name => nil

# with both joins and includes,
# this just returns a Like record, 
# with no info from User:
p @likes
  • 为什么两个查询返回的对象不同?
  • 为什么我在登录控制台时看不到来自 joins 查询的任何用户信息?
  • 我知道includes 做了一些急切加载。我上面的joins 查询是否在某些方面效率低下?

【问题讨论】:

    标签: mysql ruby-on-rails ruby-on-rails-5


    【解决方案1】:
    • joins 是一个实际的 SQL 联合,允许您查询嵌套模型。一个连接的可用数据是两个连接表的所有数据。
    Like.joins(:user).where(user: { email: "your@email.com"})
    

    如果有多个相同的名称(例如时间戳,例如created_at/updated_at),您可以使用前面的表和 joins(:user).where('users.created_at &lt; ?', Time.zone.now) 之类的 where 子句访问每个名称

    • includes 用于预先加载嵌套数据,以避免 n+1 查询。它确实不与另一个表连接(这就是likes.username 返回nil 的原因(它实际上应该引发错误,除非您在模型上委托属性我猜)。
    Like.includes(:user).map do |l|
      l.user.email
    end
    

    如果需要,您可以同时使用两者

    Like.joins(:user).includes(:user).where(user: { email: "your@email.com"}).map do |l|
      l.user.id
    end
    
    # just for example because there is an easier way to do it of course
    # Like.joins(:user).where(user: { email: "your@email.com"}).pluck(:id)
    
    

    我想说这应该回答你所有的 3 个问题。 ?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 2016-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-28
      相关资源
      最近更新 更多