I’m a total Rails newbie and i’ve been struggling for hours today
with one (prolly very silly) problem:
I have a table portfolios that has many images:
class Portfolio < ActiveRecord::Base
class Image < ActiveRecord::Base
In the controller i define a list of active portfolios:
@active_portfolios = Portfolio.find_all_by_is_active(“1”)
In the view i render the list of portfolios:
<%= render :partial => “portfolio_list”, :collection =>
in the partial collection _portfolio_list i need to get the
image_url of the first image of the portfolio:
This works fine if every portfolio has at least one image assigned to
it. However, if a portfolio doesn’t have any images yet, the whole
thing falls apart and the app exits with the error:
“You have a nil object when you didn’t expect it!”
I tried to get around it by doing this in the portfolio model:
self.images.image_url || “default.jpg”
and then in the partial:
but the exact same thing happens. If every portfolio has at least one
image it works well, if not, the error comes up. How can i avoid
errors on nil objects and instead define alternatives (e.g.
default.jpg) if a child attribute does not exist ?
Thanks for your help.