Rails:如何在另一个命名空间中的控制器中创建类的对象?

时间:2017-07-09 12:26:32

标签: ruby-on-rails ruby file-upload ruby-on-rails-5 carrierwave

我正在使用 CarrierWave AngularJS 客户端上传文件。为 carrierWave 生成的上传器位于另一个命名空间中,而控制器位于另一个命名空间中。< /强>

因此,当我在控制器中尝试创建 上传者对象时,我正在获取以下错误

uninitialized constant Api::V1::ProductsController::FileUploader

这是我的目录结构:

app
|--controllers
   |--api
      |--controllers
         |--api
            |--v1
               |--products_controller.rb
|--uploaders
   |--file_uploader.rb

产品控制器

  class Api::V1::ProductsController < ApplicationController
    respond_to :json

  ......

  def createFromExcel
    puts "------------------------------------"
    puts params[:file]
    puts "------------------------------------"
    uploader = FileUploader.new
    uploader.store!(params[:file])
  end


end

FileUploader类:

class FileUploader < CarrierWave::Uploader::Base

  # Include RMagick or MiniMagick support:
  # include CarrierWave::RMagick
  # include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:
  storage :file
  # storage :fog

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  # Provide a default URL as a default if there hasn't been a file uploaded:
  # def default_url(*args)
  #   # For Rails 3.1+ asset pipeline compatibility:
  #   # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
  #
  #   "/images/fallback/" + [version_name, "default.png"].compact.join('_')
  # end

  # Process files as they are uploaded:
  # process scale: [200, 300]
  #
  # def scale(width, height)
  #   # do something
  # end

  # Create different versions of your uploaded files:
  # version :thumb do
  #   process resize_to_fit: [50, 50]
  # end

  # Add a white list of extensions which are allowed to be uploaded.
  # For images you might use something like this:
   def extension_whitelist
     %w(xlsx xls)
   end

  # Override the filename of the uploaded files:
  # Avoid using model.id or version_name here, see uploader/store.rb for details.
  # def filename
  #   "something.jpg" if original_filename
  # end

end

如何在控制器中创建 FileUploader类的对象?

2 个答案:

答案 0 :(得分:0)

尝试使用uploader = ::FileUploader.new

答案 1 :(得分:0)

要从main(&#34;全局命名空间&#34;)而不是当前模块嵌套(&#34;命名空间&#34;)引用常量,请使用:: < / p>

class Api::V1::ProductsController < ApplicationController
  respond_to :json

  # use snake_case not camelCase
  def create_from_excel
    uploader = ::FileUploader.new
    uploader.store!(params[:file])
  end
end

请参阅: