has_many and belongs_to question

Hi,
  I have two tables, "users" and "users_emails".

users have the following columns: |id|name|
users_emails have the following columns: |user_id|email|

The classes look like the following:
class UsersEmail< ActiveRecord::Base
  belongs_to :users
end

class User< ActiveRecord::Base
  has_many :users_emails
end

Try this:

UserMail.find_by_email("foo@bar.com").collect(&:user)

It returns an array with all users with email "foo@bar.com". Do you
want this?

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("...")

Dirk.

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.

Thanks again.

deegee wrote:

It's a example of ruby sugar code ^^

"UserMail.find_by_email("f...@bar.com").collect(&:user)"
and
"UserMail.find_by_email("foo@bar.com").collect { |var| var.user }"

is the same code. I think it's useful and it haves some other uses.

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)

Fred