awenkhh
awenkhh

Reputation: 6131

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!

Upvotes: 3

Views: 5901

Answers (2)

Artem Kiselev
Artem Kiselev

Reputation: 66

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).

Upvotes: 5

awenkhh
awenkhh

Reputation: 6131

I could not find the solution why the above code does not work, but I created a new model called DataFile and a new uploader called FileUploadUploader. This is actually working. So I guess there could be a naming conflict, because I called the model Upload. But this is really just a guess ...

Upvotes: 0

Related Questions