RegistrationsController#create中的ActiveSupport :: MessageVerifier :: InvalidSignature

时间:2019-07-18 23:59:35

标签: ruby devise rails-activestorage ruby-on-rails-6

我目前正在安装ActiveStorage的Rails 6应用程序上工作。我正在使用devise进行身份验证。尝试在注册表单上创建新用户时出现以下错误。

ActiveSupport::MessageVerifier::InvalidSignature in RegistrationsController#create

我认为原因来自尝试为模型User设置默认头像。创建用户后,我正在尝试将astronaut.svg设置为默认头像。

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  has_many :posts
  has_one_attached :avatar

  before_create :set_defaults

  def set_defaults
    self.avatar = 'assets/images/astronaut.svg' if self.new_record?
  end
end

如何解决?

1 个答案:

答案 0 :(得分:1)

此代码对我有用:

def set_defaults
  if self.new_record?
    self.avatar = Rack::Test::UploadedFile.new(
      Rails.root.join('app/assets/images/astronaut.png'),
      'image/png',
    )

    # file = File.new(Rails.root.join('app/assets/images/astronaut.png'))
    # self.avatar = Rack::Test::UploadedFile.new(
    #   file.path,
    #   Mime::Type.lookup_by_extension(File.extname(file).strip.downcase[1..-1]).to_s,
    # )
  end
end

但是,我建议不要在before_create中发送默认图像,而应使用助手:

def user_avatar(user)
  if user.avatar.attached?
    image_tag user.avatar
  else
    image_tag 'astronaut.png'
  end
end