简体   繁体   English

你如何在带有 PostgreSQL 的 Rails 中查询 3 个不同的模型?

[英]How do you query 3 different models in Rails w/ PostgreSQL?

I need to write a query in Rails that involves 3 different models.我需要在 Rails 中编写一个涉及 3 个不同模型的查询。 I need to know which Subscriptions are delivereable.我需要知道哪些订阅是可交付的。 But delivereable is not a column in Subscription but in BasePlan.但是可交付成果不是 Subscription 中的列,而是 BasePlan 中的列。

class BasePlan
  has_many :plans
end

class Plan
  has_many :subscriptions
end

class Subscription
  belongs_to  :plan
end

I've tried joining all three models together to no success:我尝试将所有三个模型结合在一起但没有成功:

Subscription.joins(:plans).joins(:base_plans).where(queried_column: true)

What would be the right way to write the query?编写查询的正确方法是什么?

Subscription needs to know about it's relationship to :base_plans for your code to work. Subscription需要知道它与:base_plans的关系才能使您的代码正常工作。

class Subscription
  belongs_to :plan
  has_one :base_plan, through: :plan
end

Using @SteveTurczyn 's answer, you could query like this: Subscription.joins(:base_plan).where(base_plans: { queried_column: true }) .使用@SteveTurczyn 的回答,您可以这样查询: Subscription.joins(:base_plan).where(base_plans: { queried_column: true }) You need to first define the through relationship as Steve suggests, then you can traverse the relationship to get the column you need to check on BasePlan.您需要首先按照史蒂夫的建议定义直通关系,然后您可以遍历关系以获取您需要在 BasePlan 上检查的列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM