I need to look up a user, but also join it with another table (partner). Here's the working code without the join:
result = Repo.get_by(User, login: auth.info.email)
The user table has a foreign key with the partner table, so I thought to try this:
result = Repo.get_by(User, %{ login: auth.info.email, join: :partner } )
But this results in:
field `User.join` in `where` does not exist in the schema in query:
so it's obviously taking the join as a column name. I don't want to preload, because - as I understand - this will load the entire table in memory, and it can get big, so I need a join at the database level.
Preloading does not load the whole table in memory, but only the records where the specific foreign key matches the given struct's id.
Assuming
:partner
is either abelongs_to
orhas_many
orhas_one
relationship ofUser
, you can load it like this:If you're relying on
Repo.get_by
to return anil
on no record found, you'll need to handle that case yourself sinceRepo.preload
will raise an error if you pass itnil
as the first argument:After either of these, you can access
partner
asuser.partner
.