Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Carrierwave NoMethodError: undefined method `name' for nil:NilClass:

There is already a similar question here Rails + CarrierWave: NoMethodError: undefined method `name' for nil:NilClass but the solution there was to fix a typo.

I am already using Rails and Carrierwave in the same project with no problems. There is a simple AR model:

class Upload < ActiveRecord::Base
  attr_accessible :title, :data_file, :caption
  mount_uploader :upload, DataFileUploader

  validates :title, :data_file, :presence => true
end

In the controller thers is as usual:

def create
  @upload = Upload.new(params[:upload])

  if @upload.save
    redirect_to new_admin_upload_path, :notice => t("site.successfully_created_resource")
  else
    render :action => 'new'
  end
end

Straight forward. When submitting the form the following error occures:

ActiveRecord::StatementInvalid in Admin::UploadsController#create

NoMethodError: undefined method `name' for nil:NilClass: INSERT INTO "uploads" ("caption",    
"created_at", "data_file", "title", "updated_at") VALUES (?, ?, ?, ?, ?)

I don't see the error and don't understand, where name comes from. When leaving away mount_uploader :upload, DataFileUploader in the AR model, everything works fine.

What is wrong here?

Thanks a lot!

like image 312
awenkhh Avatar asked Dec 08 '25 07:12

awenkhh


1 Answers

I had exactly the same error and the solution was to connect uploader to existing field in my model. For your example the fix will be to change from

class Upload < ActiveRecord::Base
  attr_accessible :title, :data_file, :caption
  mount_uploader :upload, DataFileUploader

  validates :title, :data_file, :presence => true
end

to

class Upload < ActiveRecord::Base
  attr_accessible :title, :data_file, :caption
  mount_uploader :data_file, DataFileUploader

  validates :title, :data_file, :presence => true
end

if you have data_file field in Upload model and don't have upload field (examining your db/schema.rb file will be helpful).

like image 89
Artem Kiselev Avatar answered Dec 10 '25 01:12

Artem Kiselev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!