pinkfloyd90
pinkfloyd90

Reputation: 678

SQL query works but ActiveRecord syntax returns errors or an empty relation

CreditCard belongs_to User. Subscription also belongs_to User. A User has_one Subscription and has_many CreditCards.

I need to query CreditCards that belong to a User whose Subscription.status is "authorized".

This is the query that is working for me:

select * from credit_cards
join users on users.id = credit_cards.user_id
join subscriptions on users.id = subscriptions.user_id
where subscriptions.status = 'authorized'

But when I do CreditCard.joins(:user).joins(:subscription) even without the where clause, I get an empty relation:

#<CreditCard::ActiveRecord_Relation:0x2ace5a5be2f0>

If I append .emtpy to the query result, I get:

Can't join 'CreditCard' to association named 'subscriptions'; perhaps you misspelled it?

Why is it not working?

Upvotes: 0

Views: 80

Answers (2)

potashin
potashin

Reputation: 44581

As your associations are chained through one to another, you should do the following:

CreditCard.joins(user: :subscription)
          .where(subscriptions: { status: :authorized })

Upvotes: 2

zswqa
zswqa

Reputation: 914

CreditCard.joins(user: :subscription)

For more info about joins, see part 12.1.3 Joining Multiple Associations in https://guides.rubyonrails.org/v5.0/active_record_querying.html#joins

Upvotes: 2

Related Questions