Rails Carrierwave url is nil unless queried again

282 Views Asked by At

I am having an issue with carrierwave/active-record in my rails application. My problem is that the following code resolves all of the images to null

<% Ad.all.limit(30).each do |ad| %>
    <img src="<%= ad.carrier_image.url %>" >
<% end %>

Where as the following renders all the images just fine

<% Ad.all.limit(30).each do |ad| %>
    <img src="<%= Ad.find(ad.id).carrier_image.url %>" >
<% end %>

The urls are there, just on the initial loop the carrier_image does not seem to be preloaded into the active record objects I think this is an issue with my understanding of rails eager loading, but I am having trouble figuring out how one would avoid this issue

1

There are 1 best solutions below

0
On

What happens when you use the rails image_tag helper? You're also missing the brackets off the url call as per the carrierwave documentation, but I don't think that's what's causing you drama.

 <%= image_tag ad.carrier_image_url() %>

As a side note, you should really move the "Ad.all.limit(30)" out of your view if you wish to keep it all "railsy".