0

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

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

怎么修?

4

1 回答 1

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
于 2019-07-19T03:30:30.027 回答