微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby-on-rails – Rails Carrierwave:如何链接到文件?

我有一个目录,其中包含一个名为file的属性

class Catalog < ActiveRecord::Base
  mount_uploader :file,CatalogUploader

如何创建一个在浏览器中显示文件链接

我试过了

<%= link_to "zzzz",catalog.file_url %>

但当我点击该链接时,它只是给我一个路由错误

Routing Error

No route matches [GET] "/Users/emai/Documents/mysite/catalogs/2/vegetarian.png"

并且URL看起来也不正确:http:// localhost:3000 / Users / emai / Documents / mysite / catalogs / 2 / vegetarian.png.我知道pic存在,因为我创建了一个下载文件链接,并且工作正常.但是,我想要显示图片.

CatalogUploader:

# encoding: utf-8

class CatalogUploader < 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
    if Rails.env.test? || Rails.env.cucumber?
      "#{Rails.root}/public/test/file_uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
    else
      "#{Rails.root}/catalogs/#{model.id}"
    end
  end

  # Provide a default URL as a default if there hasn't been a file uploaded:
  # def default_url
  #   # 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 :scale => [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_white_list
  #   %w(jpg jpeg gif png)
  # 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

解决方法

更新CatalogUploader中的store_dir方法,如下所示:

def store_dir
    if Rails.env.test? || Rails.env.cucumber?
      "#{Rails.root}/public/test/file_uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
    else
      "#{Rails.root}/public/catalogs/#{model.id}"  ## Should be in public folder
    end
  end

图像必须存在于公共文件夹中,以便可以从Web访问它们.如果不是,那么Rails会尝试在routes.rb中找到它的路由.

另外,我认为您需要更改目录模型,如下所示:

class Catalog < ActiveRecord::Base
  mount_uploader :file,CatalogUploader,mount_on: :file

根据文档:

:mount_on => Symbol

if the name of the column to be serialized to differs you can override it using this option

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐