Ahh. this works ok in my show view because it looks for only one record
for the id. How do I show the correct company name for each contact row
in my list table of all contacts which have a belongs_to :company
association.
Ahh. this works ok in my show view because it looks for only one record
for the id. How do I show the correct company name for each contact row
in my list table of all contacts which have a belongs_to :company
association.
If your associations are correct, you should be able to use e.g. contact.company.company_name .
Using Walters solution has worked. contact.company.try(:company_name)
So my understanding of this now is that because some of the contact
records have no company defined (a nil object or NilClass). By using
.try it responds nil if no company is found.
So does that mean that if I have a field that uses a foreign key but is
not required I should use eg. try(*a, &b)? Or is there another solution?
In the console doing contact = Contact.find(1) finds my contact and the
contact.company.company_name returned the correct company name.
Having contact.company.company_name in the index.html file returns an
error:
undefined method `company_name’ for nil:NilClass
Unstated assumption: in your “index” page you’re doing something like
<% @contacts.each |contact| do %>
<%= contact.company.company_name %>
<% end %>
If not, no, of course not, “contact” isn’t defined. Cargo-culting
example
code into your project isn’t going to help; you need to think about what
it’s intended to do.
Using Walters solution has worked. contact.company.try(:company_name)
So my understanding of this now is that because some of the contact
records have no company defined (a nil object or NilClass). By using
.try it responds nil if no company is found.
So does that mean that if I have a field that uses a foreign key but is
not required I should use eg. try(*a, &b)? Or is there another solution?
First, is it OK that a contact has no company, or is that a data error
that should have been caught by validations?
If it’s OK to have a nil company association, then the question is: how
many of these potential error-generating statements do you have? If
it’s only one or two, you can use the try approach above or
Use a rescue:
contact.company.company_name rescue ‘’
Test for the existence of company:
if contact.company
contact.company.company_name
end
Write a helper to return empty values for nil companies:
untested example follows
company_info_for(contact.company, ‘’)
replaces contact.company.company_name in view
def company_info_for(company, attr)
defaults = { :company_name => '' }
return defaults'attr] if company.nil?
company.send(attr)
end