Re: [Rails] Re: Find Company Name not ID
On Sat, Jul 21, 2012 at 7:44 PM, James Harris <lists@ruby-forum.com> wrote:
> 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
1) Use a rescue:
contact.company.company_name rescue ''
2) Test for the existence of company:
if contact.company
contact.company.company_name
end
3) 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
--
Hassan Schroeder ------------------------ hassan.schroeder@gmail.com
http://about.me/hassanschroeder
twitter: @hassan
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home