Rasna Shakya
Rasna Shakya

Reputation: 557

NoMethodError: undefined method `body' for nil:NilClass

I am trying to rename uploaded file and here is my code on image_uploader.rb:

def filename
    if !cached? && file.present? 
      new_filename = 'wow.jpg'
      new_path = File.join(File.dirname(file.path), new_filename)
      new_sf = CarrierWave::SanitizedFile.new(new_path)
      cache!(new_sf)
      recreate_versions!
      new_filename
    else 
      super 
    end 
  end

While doing

recreate_versions!

i got into this error:

NoMethodError: undefined method `body' for nil:NilClass

Upvotes: 1

Views: 2252

Answers (2)

Philip
Philip

Reputation: 21

In my case, I am getting this issue when the file being processed does not exist. I fixed it by adding a condition(file.file.exists?) to check whether the file exists or not calling recreate_versions!.

  • Original codes(ruby):

file.recreate_versions! if file.present? && crop_x.present?

  • Updated codes(ruby):

file.recreate_versions! if file.present? && crop_x.present? && file.file.exists?

Upvotes: 0

MrShemek
MrShemek

Reputation: 2483

If you are trying to rename the file that was already uploaded and stored, you can use move_to method (documentation).

Let's assume that you have a User model with Carrierwave mounted for an avatar. Then, from the rails console, you can call:

User.find(1).avatar.path
=> /path/to/avatar/1/image.jpg

User.find(1).avatar.file.move_to("/path/to/avatar/1/new_image_name.jpg")

User.find(1).avatar.path
=> /path/to/avatar/1/new_image_name.jpg

No custom code is needed and your problem should be solved.

Upvotes: 0

Related Questions