1

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?

2
  • What are all of the columns you're checking? If you're looking for a base plan then why not jsut start on that model without all the joins? Commented Oct 8, 2020 at 16:04
  • I should've added more context. I need to know which Subscriptions are delivereable. But delivereable is not a column in Subscription but in BasePlan. Commented Oct 8, 2020 at 17:10

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Thanks! That worked! Thanks for the explanation as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.