"#<ActionDispatch::Http::UploadedFile:0x007f8b6134d610>":字符串的未定义方法 'url'



我正在使用carrierwave上传图片。

undefined method `url' for "#ActionDispatch::Http::UploadedFile:0x007f8b6134d610>":String
<%= image_tag @product.picture.url if @product.picture? %> 

这是我的代码:

_form.html.erb

<div class="picture">
    <%= f.file_field :picture %>
  </div>

product.rb

class Product < ApplicationRecord
  has_many :reviews, dependent: :destroy
  mount_uploader :picture, PictureUploader  
end

show.html.erb

<p id="notice"><%= notice %></p>
<p>
  <strong>Name:</strong>
  <%= @product.name %>
</p>
  <strong>Picture:</strong>
  <%= image_tag @product.picture.url if @product.picture? %>
</p>
<%= link_to 'Edit', edit_product_path(@product) %> |
<%= link_to 'Back', products_path %>

有人知道如何解决问题吗?

更新:

picture_uploader.rb

# encoding: utf-8
class PictureUploader < 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
  #   # 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_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

这是gemfile中的版本:

gem 'carrierwave',             '0.11.2'
gem 'mini_magick',             '4.5.1'
gem 'fog',                     '1.38.0'

我会检查第一个强参数,并添加 :picture属性,如果没有添加。

然后,我会尝试在您的节目视图中添加它:

show.html.erb

<%= image_tag(@product.picture_url.to_s) %>

而不是这线代码:

<%= image_tag @product.picture.url if @product.picture? %>

如果您有权限问题,则可以创建配置文件:

config/initializers/carrierwave.rb

并添加权限:

CarrierWave.configure do |config|
  config.permissions = 0666
  config.directory_permissions = 0777
  config.storage = :file
end

在模型中,您需要添加

blockquotemount_uploader:图片,pictureuploaderblockquote

最新更新