blackghost
blackghost

Reputation: 713

Scope relying on association in Rails?

I have the following associations:

Order belongs_to OrderStatus

I want to have an Order scope that would give me all the Orders which OrderStatus is 'ready'.

OrderStatus has an attribute called name, and that is where the 'ready' is.

So, I have tried this:

scope :ready, -> { where('order_status.name = ?', 'ready') }

But it is not working as expected. PG::UndefinedTable: ERROR: missing FROM-clause entry for table "order_status"

Upvotes: 0

Views: 23

Answers (1)

Nobita
Nobita

Reputation: 23711

You want to join the associated (order_status) model:

scope :ready, -> { joins(:order_status).where('order_statuses.name' => 'ready') }

Upvotes: 1

Related Questions