我得到错误未定义的方法`to_sym' for nil:Rails中的NilClass用于更新图像?

时间:2017-11-06 04:17:56

标签: ruby-on-rails

我的控制器

def update
    handled_error_fields %i(location address1 address2 name name_kanji gender prefecture_code tel zip_code).collect { |s| :"primary_address.#{s}" }

    if params[:salon].present?
      if params[:salon].present?
        if params[:salon][:tel].present?
          tel = params[:staff][:tel]
          params[:staff][:tel] = NKF.nkf('-W -w -m0 -Z0', tel)
        end
      end
      if params[:staff][:email].present?
        email = params[:staff][:email]
        email.gsub!(/。/, '.')
        params[:staff][:email] = NKF.nkf('-W -w -m0 -Z0', email)
      end
    end

    if params[:staff]["staff_image"].present?
      @staff_image = StaffImage.find_by_staff_id(current_staff.id)
       if @staff_image.blank?
        @staff_image = StaffImage.new 
        @staff_image.staff_id = current_staff.id
        @staff_image.legacy_user_id = current_staff.legacy_user_id    
        @staff_image.image = params[:staff]["staff_image"]["image"].read
        @staff_image.save!
      else

        @staff_image.image = params[:staff]["staff_image"]["image"].read
        @staff_image.update_attribute('image', @staff_image.image)
       end
    end
    super
  end

我的模特是

class StaffImage < ActiveRecord::Base

end

它有列 staff_idimagelegacy_client_id

真正的问题是在数据库中插入图像后,我无法更新图像。我是Rails的新手。我知道问题在于这一行:

@staff_image.update_attribute('image', @staff_image.image)

3 个答案:

答案 0 :(得分:0)

不使用任何附件插件?看看https://github.com/thoughtbot/paperclip gem。在Rails中处理这类事情的方式太容易了。

答案 1 :(得分:0)

不必使用update_attribute方法。简单的保存可以解决。

@staff_image.image = params[:staff]["staff_image"]["image"].read 
@staff_image.save

答案 2 :(得分:0)

您可能想尝试调用&#34; with_indifferent_access&#34;像:

params = params.with_indifferent_access

在访问&#34; staff_image&#34;

之前
params[:staff]["staff_image"]["image"]

这应该摆脱错误,然后:

@staff_image.image = params[:staff]["staff_image"]["image"].read 
@staff_image.save