“#”的未定义方法“url”:字符串

2024-03-30

我使用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>

产品.rb

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

显示.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 %>

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

Update:

图片上传器.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属性(如果尚未添加)。

然后我会尝试将其添加到您的显示视图中:

显示.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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

“#”的未定义方法“url”:字符串 的相关文章

随机推荐