Reputation: 1040
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
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
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