On Sat, Dec 26, 2009 at 3:20 PM, Matt Harrison
<[email protected]> wrote:
> I've got a relationship:
>
> Person has many MiddleNames
> and
> MiddleName belongs to Person
>
>
> In irb I can add a person, add a middle name then call
>
> @person.middle_names.first.name

And what happens if you don't add a middle name.

[].first #=> nil

>
> to get that middle name. However when I try the exact same code in a view, I
> get
>
> undefined method `name' for nil:NilClass
>
> If I iterate through like so:
>
> for mname in @person.middle_names
>  puts mname.name


Because if @person.middle_names is empty the loop body is not executed.

>
> Then it works perfectly, but for some reason using ".first" is failing in
> the view. I've used this method many many times and never come across
> anything quite like this.
>
> I believe I'm probably overlooking some incredibly simple answer and I'm
> going to kick myself when someone points it out, but for now I'm completely
> stumpted.
>
> Any input appreciated.
>
> Thanks
>
> Matt
>



-- 
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale

--

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 [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.


Reply via email to