Hi,
There are quite a few inconsistencies in your code, not sure if they
are typos in the post or actual errors in your code. You should have
class UsersEmail < AR::Base
belongs_to :user # note the singular here!
end
Then you say you have a user_emails table: If your class is
UsersEmail, your table should be users_emails (users is plural). I
think class UserEmail would be more appropriate naming, but that's up
to you.
David's code is then most elegant to fetch all users with a particular
e-mail address. To address why your own code is not working:
emails = UsersEmail.find(:conditions => ...) will return you an Array
of UsersEmail objects. So if you want to construct an Array of User
objects from that, you need to indeed to apply a .collect or .map to
it:
foundusers = emails.map { |e| e.user } # note the singular user due to
the belongs_to clause
Again, instead of using :conditions, you can use a dynamic finder if
all you need is find on a specific column's content:
UsersEmail.find_by_email("...")
Hi,
Thanks for the quick respones. David's answer works great.
I'm still new to Rails, I was wondering what ":&user" does? I know the
collect method applies ":&user" to all the elements in the hash.
Hi,
Thanks for the quick respones. David's answer works great.
I'm still new to Rails, I was wondering what ":&user" does? I know
the
collect method applies ":&user" to all the elements in the hash.
it's &:user.
when you prefix the last argument to a function with & that tells ruby
'this is something like a proc that you should should use as the block
for this function).
I said like a proc, because ruby doesn't really care. As long as it
has a to_proc method which returns something close enough to a proc
then you're ok.
rails adds a to_proc method to symbols that generates an appropriate
proc (from 1.8.7/1.9 this is part of the standard library (not 100%
sure about 1.8.7)