Undefined method `img_source' for nil:NilClass

Hi everyone

I’m quite new to Ruby/rails.

I’m getting an error when I try and read from another table/model from a
view.

If I try this:

<% @p = Post.last(:conditions => { :user_id => u.id }) %>

<%= @p.inspect %>

I get:

#<Post id: 38, user_id: 1, img_source: “http://blah.com”>

But when I try this:

<% @p = Post.last(:conditions => { :user_id => u.id }) %>

<%= @p.img_source %>

I get:

undefined method `img_source’ for nil:NilClass

But this works:

<% @p = Post.last %>

<%= @p.img_source %>

I don’t understand what I’m doing wrong.

I get the same problem too if I try and use associations but I suspect
the problem is something more obvious.

Many thanks
Richard

Richard H. wrote in post #1048333:

Hi everyone

I’m quite new to Ruby/rails.

I’m getting an error when I try and read from another table/model from a
view.

I figured it out - I was iterating over several items, some were
actually Nil. Once I checked before trying to read the attribute the
problem goes away.

Thanks