Search code examples
ruby-on-railsrubytypesattachment-fu

TypeError (Can't convert nil into String) With Attachment_Fu


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?


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!