【问题标题】:Activerecord joining syntax. Square Brackets vs Curly Brackets?Activerecord 加入语法。方括号与花括号?
【发布时间】:2016-11-30 01:51:22
【问题描述】:

这是来自 Rails 文档:

12.1.3.2 加入嵌套关联(多级)

Category.joins(articles: [{ comments: :guest }, :tags])

这会产生:

SELECT categories.* FROM categories
  INNER JOIN articles ON articles.category_id = categories.id
  INNER JOIN comments ON comments.article_id = articles.id
  INNER JOIN guests ON guests.comment_id = comments.id
  INNER JOIN tags ON tags.article_id = articles.id

或者,用英语:“返回所有有文章的类别,这些文章有客人发表的评论,以及这些文章也有标签的地方。”

所以这一切都说得通。但是如何在 ActiveRecord 中获取这个 sql:

SELECT categories.* FROM categories
      INNER JOIN articles ON articles.category_id = categories.id
      INNER JOIN comments ON comments.article_id = articles.id
      INNER JOIN guests ON guests.comment_id = comments.id
      INNER JOIN tags ON tags.comments_id = comments.id

我如何加入tags 回到comments。用英文,我想要:

"返回所有有文章的类别,这些文章有客人发表的评论,以及这些 cmets 也有标签。"

更重要的是,什么是大括号和方括号的好方法?

【问题讨论】:

    标签: activerecord


    【解决方案1】:

    我想这就是你要找的东西:

    Category.joins(articles: { comments: [:guest, :tag] })
    

    将花括号(哈希)视为连接表的嵌套条件。将方括号(数组)视为连接多个表的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-11
      • 1970-01-01
      • 1970-01-01
      • 2014-03-01
      • 2021-11-20
      • 1970-01-01
      • 2019-01-26
      • 1970-01-01
      相关资源
      最近更新 更多