Question

I'm handling file attachments in my Rails app with Attachment_fu, which provides a public_filename method to retrieve a file's URL. I'm using it on a model called Cover, so if I want to call the URL of an uploaded cover image, in a view I would do:

<%= image_tag(@cover.public_filename) %>

This works just fine when the user has the appropriate attachment, but in my application it is not a requirement for a user to upload an attachment.

Therefore, calling @cover.public_filename will throw a TypeError: Can't convert nil into String for the obvious reason that the file is nil.

However, I'm having trouble adding logic to this problem effectively since the object is nil, and all of my attempts with doing things like unless @cover.public_filename.nil? or if @cover.public_filename == nil have been fruitless and cause the same Type Error.

What am I missing?

Was it helpful?

Solution

I didn't work with attachment_fu, but as I see public_filename is method that relies on some fields that are nil when you don't have attachment attached. Here I read that attachment_fu should always has attachment - and this is probably a reason why it didn't work for you. The author also suggest using paperclip plugin. Take a look at it!

OTHER TIPS

<%= image_tag(@cover.public_filename) unless @cover.nil? %>

Sorry, can't comment, so here's an update instead:

@cover.public_filename? won't work here because @cover is a nil object and as such has no public_filename? method.

nil.respond_to?('public_filename?') #=> false

Updated:

Make it:

<%= image_tag(@cover.public_filename) if @cover && @cover.public_filename? %>

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top