beaconhill
beaconhill

Reputation: 451

Rails each skipping if nil value

I'm currently iterating through a list of arrays, referencing data from a joined record (Students):

index.html.erb

<% @activities.compact.each do |activity| %>
    <div class="img" style="background-image: url(<%= activity.student.image.url(:thumb) %>)">
<% end %>

If for some reason a user deletes the joined record (Student), Rails throws this error:

NoMethodError in Activities#index
undefined method `image' for nil:NilClass

Is there a way to tell Rails to still render the page but sub in a default value to that record if none exists?

Upvotes: 0

Views: 84

Answers (3)

Sandeep Kapil
Sandeep Kapil

Reputation: 992

Try

<% @activities.compact.each do |activity| %>
    <% if activity.student.present? %>
    <div class="img" style="background-image: url(<%= activity.student.image.url(:thumb) %>)">
    <% end %>
<% end %>

Upvotes: 0

iSunRise
iSunRise

Reputation: 106

If you use carrierwave gem for uploads, there'a built-in solution for default images https://github.com/carrierwaveuploader/carrierwave#providing-a-default-url

Upvotes: 0

Paul A Jungwirth
Paul A Jungwirth

Reputation: 24541

Sure! For example,

activity.student.try{|s| s.image.url(:thumb)} || image_path("default.png")

You might want to put that into a helper though, since it seems like it's starting to get complicated.

Also, I would be wary of XSS problems here if users control any part of the attachment URL (e.g. if you are using the filename of their uploaded file). I'm not sure whether erb does the right thing when outputting to an attribute. Maybe it does---I'm just not sure.

Upvotes: 3

Related Questions