簡體   English   中英

Rails + Carrierwave:如何鏈接到文件?

[英]Rails + Carrierwave: How to link to file?

我有一個Catalog ,其中包含一個名為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

根據文檔 ,你應該像這樣調用文件對象的方法url

<%= link_to "zzzz", catalog.file.url %>

更新store_dir的方法CatalogUploader如下:

 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

圖像必須存在於public文件夾中,以便可以從Web訪問它們。 如果不是,那么Rails會嘗試在routes.rb找到它的路由。

另外,我認為您需要更改Catalog模型,如下所示:

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

根據文檔:

:mount_on =>符號

如果要序列化的列的名稱不同,則可以使用此選項覆蓋它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM