【问题标题】:Carrierwave NoMethodError: undefined method `name' for nil:NilClass:Carrierwave NoMethodError:nil 的未定义方法“名称”:NilClass:
【发布时间】:2012-03-06 23:45:23
【问题描述】:

Rails + CarrierWave: NoMethodError: undefined method `name' for nil:NilClass 这里已经有一个类似的问题,但解决方案是修复一个错字。

我已经在同一个项目中使用 Rails 和 Carrierwave,没有任何问题。有一个简单的 AR 模型:

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

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

在控制器中和往常一样:

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

直截了当。提交表单时出现以下错误:

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 (?, ?, ?, ?, ?)

我没有看到错误,也不明白名称的来源。在 AR 模型中离开 mount_uploader :upload、DataFileUploader 时,一切正常。

这里有什么问题?

非常感谢!

【问题讨论】:

标签: ruby-on-rails carrierwave


【解决方案1】:

我遇到了完全相同的错误,解决方案是将上传器连接到我模型中的 existing 字段。对于您的示例,修复将从

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

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

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

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

如果您在上传模型中有 data_file 字段但没有上传字段(检查您的 db/schema.rb 文件会有所帮助)。

【讨论】:

    【解决方案2】:

    我找不到上述代码不起作用的解决方案,但我创建了一个名为 DataFile 的新模型和一个名为 FileUploadUploader 的新上传器。这实际上是有效的。所以我猜可能存在命名冲突,因为我调用了模型上传。但这真的只是猜测……

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-02
      • 1970-01-01
      • 2016-01-31
      • 2011-07-11
      • 1970-01-01
      相关资源
      最近更新 更多