Calling data from different model in Rails

Posted by Danny McClelland on Stack Overflow See other posts from Stack Overflow or by Danny McClelland
Published on 2010-04-28T13:31:45Z Indexed on 2010/04/28 14:03 UTC
Read the original article Hit count: 303

Filed under:
|

Hi Everyone,

I need to be able to call data from a different model - not just one field, but any of them.

At the moment I have the following models:

kase
person
company
party

I can call information from the company to the kase and from the person to the kase using this:

<li>Client Company Address: <span class="address"><%=h @kase.company.companyaddress %></span></li>
<li>Case Handler: <span><%=h @kase.person.personname %></span></li>

Those two work, however if I add the following:

<li>Client Company Fax: <span><%=h @kase.company.companyfax %></span></li>
<li>Case Handler Tel: <span><%=h @kase.person.personmobile %></span></li>
<li>Case Handler Email: <span><%=h @kase.person.personemail %></span></li>

Any idea whats wrong?

Thanks,

Danny

EDIT: I get the following error message:

NoMethodError in Kases#show
Showing app/views/kases/show.html.erb where line #37 raised:

You have a nil object when you didn't expect it!
The error occurred while evaluating nil.personname

The lines that are noted are as follows:

34: <div id="clientinfo_showhide" style="display:none">
35: <li>Client Company Address: <span class="address"><%=h @kase.company.companyaddress  %></span></li>
36: <li>Client Company Fax: <span><%=h @kase.company.companyfax %></span></li>
37: <li>Case Handler: <span><%=h @kase.person.personname %></span></li>
38: <li>Case Handler Tel: <span><%=h @kase.person.personmobile %></span></li>
39: <li>Case Handler Email: <span><%=h @kase.person.personemail %></span></li>
40: </div>

The model for the kase is as follows:

class Kase
belongs_to :company # foreign key: company_id
belongs_to :person # foreign key in join table

The model for the person is as follows:

class Person
has_many :kases # foreign key in join table
belongs_to :company

The model for the company is as follows:

class Company
has_many :kases
has_many :people
def to_s; companyname; end

Hope this helps!

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about database