Reputation: 461
I use the following code to show the email of the person to whom I sent a comment.
Controller:
@to_user = User.where(id: @comment.to_id)
View:
<%= @to_user.email %>
Only it generates an error: undefined method `email' for #<User::ActiveRecord_Relation:0x007feb364b8218>
Showing "from" user works well:
<%= @comment.user.email %>
Not sure what I am doing wrong. Help would be much appreciated.
Upvotes: 0
Views: 28
Reputation: 114178
To retrieve a single object, you use find
:
@to_user = User.find(@comment.to_id)
But it's more idiomatic to define a belongs_to
association in your Comment
model, e.g.:
class Comment < ActiveRecord::Base
belongs_to :to_user, class_name: 'User', foreign_key: 'to_id'
# ...
end
This allows you to simply write:
<%= @comment.to_user.email %>
To avoid confusion, you might want to rename the exising user
to from_user
. Or maybe use more descriptive names like sender
and receiver
.
And if you do so, it would be a good idea to also rename the columns from user_id
and to_id
to from_user_id
and to_user_id
(or sender_id
and receiver_id
).
Upvotes: 2
Reputation: 26768
.where
returns an ActiveRecord_Relation, which you can think of like an array of records (actually, the records aren't loaded yet, but as soon as you call a method like .each
or .to_a
it evaluates the query and turns it into an array).
What you are looking for is either
.find
(User.find(@comment.to_id)
) - this will raise an error if the user is not found.find_by
(User.find_by(id: @comment.to_id)
) - this will return nil if the user is not foundYou could also just call .first
on the .where
result - as often is the case in Ruby/Rails, there are many ways to do the same thing.
Upvotes: 1