如何在Rails中联接三个表?

Yuv*_*rmi 5 sql database-design join ruby-on-rails ruby-on-rails-3

我的记录设置如下

Subscription: id, plan_id                 <- belongs to plan
Plan: id, role_id                         <- belongs to role
Role: id, name
Run Code Online (Sandbox Code Playgroud)

给定此数据

Subscription: id: 1, plan_id: 5
Plan: id: 5, role_id: 10
Role: id: 10, name: 'Gold'
Run Code Online (Sandbox Code Playgroud)

我正在尝试编写一个联接,以便可以根据其关联角色来查找订阅,即:

Subscription.joins(:plan).joins(:role).where(“ roles.name =?”,'Gold')

但是这种方法行不通。任何帮助,将不胜感激。

谢谢。

Tho*_*rin 5

如果你有适当的关联,那么使用这个:

Subscription.includes(:plan => [:role]).where("roles.name = 'Gold'").first
Run Code Online (Sandbox Code Playgroud)

您也可以手动编写查询:

Subscription.joins("INNER JOIN plans ON plans.id = subscriptions.plan_id
                    INNER JOIN roles ON roles.id = plans.role_id").where("roles.name = 'Gold'").first
Run Code Online (Sandbox Code Playgroud)

  • 这称为嵌套连接,您甚至可以将其嵌套三层或更深,如下所示:`.joins(plan: [role: :person])` https://api.rubyonrails.org/classes/ActiveRecord/QueryMethods .html#method-i-joins (2认同)

Ale*_*x P 4

如果您尝试查找给定角色的所有订阅,为什么不从该角色开始呢?如果我们正确配置它们,Rails 可以处理这些“一步删除”关联。

gold_role = Role.where(name: 'Gold').first
gold_role.subscriptions
Run Code Online (Sandbox Code Playgroud)

这可以通过Rails 的has_many :through关系来实现。我认为这对于您的模型来说是正确的设置:

class Subscription < ActiveRecord::Base
  belongs_to :plan
  has_one :role, through: :plan
end

class Plan < ActiveRecord::Base
  has_many :subscriptions
  belongs_to :role
end

class Role < ActiveRecord::Base
  has_many :plans
  has_many :subscriptions, through: :plans
end
Run Code Online (Sandbox Code Playgroud)