# Problem with association

**URL:** <https://www.ruby-forum.com/t/problem-with-association/125491>\
**Category:** Rails\
**Created:** [January 9, 2008, 4:38pm UTC](https://www.ruby-forum.com/t/problem-with-association/125491 "2008-01-09T16:38:45Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![stratboy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/838e76/32.png) [@stratboy](https://www.ruby-forum.com/u/stratboy)\
**Post date:** [January 9, 2008, 4:38pm UTC](https://www.ruby-forum.com/t/problem-with-association/125491/1 "2008-01-09T16:38:45Z")

</div>

i have 2 models:

class User \< ActiveRecord::Base  
has\_many :mails  
end

class Mail \< ActiveRecord::Base  
belongs\_to :receiver ,:class\_name =\> ‘User’,:foreign\_key =\>  
‘receiver\_id’  
belongs\_to :sender,:class\_name =\> ‘User’,:foreign\_key =\> ‘sender\_id’  
end

in controller i have this:  
@messages=Mail.find(:all,:include=\>:sender,:conditions=\>“receiver\_id=#{session[:user\_id]}”,:limit=\>40,:offset=\>(params[‘page’]  
? params[‘page’] : 0))

if i put @messages[0].sender.name

i receive an error:  
You have a nil object when you didn’t expect it!  
The error occurred while evaluating nil.name

Why?

How i can do?  
Thanks

---

<div class="post-metadata">

**Author:** ![stratboy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/838e76/32.png) [@stratboy](https://www.ruby-forum.com/u/stratboy)\
**Post date:** [January 9, 2008, 5:07pm UTC](https://www.ruby-forum.com/t/problem-with-association/125491/2 "2008-01-09T17:07:25Z")

</div>

On 9 Jan 2008, at 15:38, Luca R. wrote:

> if i put @messages[0].sender.name
> 
> i receive an error:  
> You have a nil object when you didn’t expect it!  
> The error occurred while evaluating nil.name

Well the obvious reason is that you have a message with a nil  
message.sender. Is this the case ?

Fred

---

<div class="post-metadata">

**Author:** ![stratboy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/838e76/32.png) [@stratboy](https://www.ruby-forum.com/u/stratboy)\
**Post date:** [January 9, 2008, 9:10pm UTC](https://www.ruby-forum.com/t/problem-with-association/125491/3 "2008-01-09T21:10:25Z")

</div>

Here’s a hint: Your User model has\_many :mails, but a user really  
has\_many :sent\_mails and has\_many :received\_mails. You’ll need to set  
the foreign\_key attributes.
