简体   繁体   中英

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

I need to write a query in Rails that involves 3 different models. I need to know which Subscriptions are delivereable. But delivereable is not a column in Subscription but in 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.

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 }) . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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