【问题标题】:Join multiple tables with active records使用活动记录连接多个表
【发布时间】:2014-06-17 14:10:57
【问题描述】:

我想知道位于曾孙选项卡中的横幅名称。我的数据库是这样的:

Inscription (where I need to start from): Item1_id
Item1: Item2_id
Item2: Banner_id
Banners: name

如何获取我的题字表的所有横幅名称以及活动记录?

【问题讨论】:

  • Inscription.includes(item1: { item2: :banner }) item1item2banner 的名称需要与每个关系的名称匹配(例如:如果您设置了 Inscription has_many: :items2,那么您应该使用 .includes(:items2)) . (如果需要,可以使用 .joins 和相同的参数)
  • 谢谢! @MrYoshiji 如果我想添加 where(name == "") 我应该怎么做?
  • 只要在末尾加上.where(name: ""),毕竟joins/includes
  • 它不起作用:/它在“where 子句”中显示未知列“inscriptions.name”我写道: Inscription.joins(firm_office_1: {firm: :banner }).where(name: "" )

标签: sql ruby-on-rails activerecord


【解决方案1】:

您可以执行以下操作:

Inscription.includes(item1: { item2: :banner })

关系名称item1item2banner 需要与赋予每个关系的名称相匹配。

如果你想在这个查询上设置where 语句,你可以这样做:

scope = Inscription.includes(item1: { item2: :banner }) 
scope = scope.where(banner: { name: "MOTD: Hello World!" })
scope = scope.where(item2: { is_favorite: true })

类似问题:

【讨论】:

    猜你喜欢
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    相关资源
    最近更新 更多