ruby-on-rails - Rails 5 - Shrine 问题 : "undefined method ` cached_image_data' for nil:NilClass"

标签 ruby-on-rails ruby

我在尝试允许使用 Shrine 上传头像时遇到了一些问题。我正在使用 Rails 5。我不断收到错误消息,“nil:NilClass 的未定义方法‘cached_image_data’”。

我试过多次重启,并按照各种教程进行操作。据我所知,我正在做我想做的一切。 ImageUploader 已设置,我的照片模型已设置等。我在下面包含了相关的代码。

应用程序/模型/photo.rb:

class Photo < ApplicationRecord

    include ImageUploader::Attachment.new(:image) 

end

apps/uploaders/image_uploader.rb 需要“image_processing/mini_magick”

class ImageUploader < Shrine
   plugin :processing
   plugin :versions, names: [:original, :thumb, :medium]
   plugin :delete_raw # delete processed files after uploading


process(:store) do |io, context|
    original = io.download
    pipeline = ImageProcessing::MiniMagick.source(original)
    size_80 = pipeline.resize_to_limit!(80, 80)
    size_300 = pipeline.resize_to_limit!(300, 300)
    original.close!
    # return hash of 3 sizes of the same image
    { original: io, thumb: size_80, medium: size_300 }
end

结束

app/views/profiles/_form.html.erb

<%= form_with(model: profile, local: true) do |form| %>

   <div class="field">
     <%= form.label :image %>
     <%= form.hidden_field :image, value: @photo.cached_image_data %>
     <%= form.file_field :image, id: :photo_image_data %>
   </div>

<% end %>

app/controllers/profile_controller.rb

class ProfilesController < ApplicationController
  before_action :set_profile, only: [:show, :edit, :update, :destroy]
  before_action :view_own_profile, only: [:show]

  def show
  end

   private
   def set_profile
     @profile = Profile.find(params[:id])
   end

def profile_params
  params.require(:profile).permit(:first_name, :last_name, :mobile, 
  :street_address, :suburb, :postcode, :country, :mobile, :image, 
  :latitude, :longitude, :user_id)
end

结束

如有任何帮助,我们将不胜感激。如果需要任何其他信息,请告诉我。

干杯, 创

最佳答案

您应该在 Controller 中设置@photo 变量。如果因为它不存在而无法设置,您可能需要在表单中调用 @photo&.cached_image_data(注意 &)。这和调用 @photo.nil 一样吗? ? nil :@photo.cached_image_data 在调用 #cached_image_data 之前检查 @photo 是否不是 nil。如果 @photonil,则使用 nil 的值,并且永远不会调用 #cached_image_data

请参阅 2.3.0 release notes 的“安全导航运算符”部分.

关于ruby-on-rails - Rails 5 - Shrine 问题 : "undefined method ` cached_image_data' for nil:NilClass",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50189037/

相关文章:

ruby-on-rails - rails 中的单元测试 - 带回形针的模型

jquery - 使用 jQuery、jEditable、jeditable-rails gem 或任何 AJAXy 解决方案使表行可编辑

ruby-on-rails - 没有路由匹配 [POST] "/sessions/user"

ruby - ncurses 到外壳并返回弄乱键

ruby-on-rails - 如何返回基于一天的 future 日期列表(例如,星期一到年底的日期)?

在 gdb 中暂停的 Ruby 程序在使用 rb_eval_string 写入任何 IO 后无法恢复

ruby - REXML 格式问题

ruby-on-rails - Cancan用户权限?

ruby - 守护进程不会重新启动?

javascript - 使用 Angular 进行动态路由 - 如何使用此 JSON?