S.S.J
S.S.J

Reputation: 363

Nested association in a where clause doesn't produce valid SQL

I have following models

class User < ActiveRecord::Base
  has_many :documents
  has_many :requests
end

class Document < ActiveRecord::Base
  has_many   :requests
  belongs_to :user
end

class Request < ActiveRecord::Base
  belongs_to :document
  belongs_to :requester, class_name: 'User', foreign_key: 'user_id'
end

Basically, there are users which can have many documents. Users can request access to documents of other users.

Now I want to get list of requests with specific status which were sent to a user.

This query executed in a method of User doesn't work

Request.includes(:document)
       .where(status: Request::SOME_STATUS, documents: { user: self })

I get error

ERROR: column documents.user does not exist

It obviously can be fixed by replacing user: self with user_id: id, but I don't understand why Active Record doesn't work with user: self. Is this behavior documented?

Upvotes: 1

Views: 104

Answers (1)

Mohamad
Mohamad

Reputation: 35349

A Request belongs to a document, so this part of your query is not valid in this context: documents: { user: self }

From the documentation:

In the case of a belongs_to relationship, an association key can be used to specify the model if an ActiveRecord object is used as the value.

What this implies is that for self to work, the relationship has to be belongs_to so that you could fetch requests that belong to a particular document.

The reason user: id works is because the documents table happens to have a user_id column.

Upvotes: 1

Related Questions