Mike Bonds
Mike Bonds

Reputation: 1040

How to find a model using a nested attribute

I have a User Model that has nested attributes.

One of these nested attributes is email.

Is it possible to find a user model by using the email address that is found in the nested attributes?

So something similar to User.find_by(email: "[email protected]") but looks at the nested email attribute instead of directly at the top level user model.

Thanks in advance!

Upvotes: 2

Views: 1118

Answers (2)

MilesStanfield
MilesStanfield

Reputation: 4639

Given that User has_many :emails and Email table has address column

you can use includes to do what you want

User.includes(:emails).where(emails: { address: '[email protected]' })

Upvotes: 5

Tim
Tim

Reputation: 1005

So, if you have email as a nested attribute it implies a has_one or has_many relationship from user to email

The reverse of that is belongs_to. E.g.

belongs_to :user

In your email class. With that in place, you can simply do:

Email.find_by(email: '[email protected]').user

Upvotes: 0

Related Questions