Rails 4中使用Devise和Paperclip,文件保存错误

3
我正在使用devise gem和paperclip处理身份验证和上传图片。问题是我在同一个模型上两次使用了paperclip来存储两张图片(我们称这些paperclip列为:avatar,superbadge),我的模型名称为User。
现在,当我选择上传两张图片时,我的rails应用程序会忽略我选择的第一张文件,而是使用第二个选择的文件并将其保存在第一个paperclip列中,使第二个paperclip列为空。如何解决?
我的应用程序控制器:
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  before_action :configure_devise_permitted_parameters, if: :devise_controller?

  protected

    def configure_devise_permitted_parameters
        registration_params = [:name, :email, :password, :password_confirmation,:avatar,:superstarbadge]

        if params[:action] == "update"
          devise_parameter_sanitizer.for(:account_update) {
            |u| u.permit(registration_params << :current_password)
          }
        elsif params[:action] == "create"
          devise_parameter_sanitizer.for(:sign_up) {
            |u| u.permit(registration_params)
          }
        end 
    end
end

我的 User.rb 模型:

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable, :validatable
  has_attached_file :avatar, :styles => { :small => "100x100>" }
  validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/

  has_attached_file :superstarbadge, :styles => { :tiny => "100x100>" }, :default => "superbadge.jpg" 
  validates_attachment_content_type :superstarbadge, :content_type => /\Aimage\/.*\Z/

  has_many :questions
  has_many :answers

  def to_s
    email
  end
end

使用Devise Gem创建新用户的表单,我的模板语言是Slim而非ERB:

h1 Sign up

= form_for(resource, as: resource_name, url: registration_path(resource_name), :html => { :multipart => true }) do |f|
  = devise_error_messages!

  .field
    label= f.label :name
    = f.text_field :name, autofocus: true

  .field
    label= f.label :email
    = f.email_field :email, autofocus: true

  .field
    label= f.label :password
    = f.password_field :password, autocomplete: 'off'

  .field
    label= f.label :password_confirmation
    = f.password_field :password_confirmation, autocomplete: 'off'

  .field
    = f.label :avatar
    = f.file_field :avatar

  .field 
    = f.file_field :avatar

  div
    = f.submit "Sign up"

你的两个 file_field 都是用于 :avatar,难道你不想其中一个用于 :superbadge 吗? - JTG
我需要新眼镜,谢谢 :) - Matthew
1个回答

4

您的表单中的两个file_field都指向avatar字段,因此当您提交表单时,第二个选择的文件(即latest)将保存为avatar。没有file_field用于superstarbadge,因此它永远不会被保存。

您需要一个file_field用于avatar,另一个用于superstarbadge。因此,您的代码应如下所示:

.field
  = f.label :avatar
  = f.file_field :avatar

.field 
  = f.file_field :superstarbadge ## This one should be superstarbadge and NOT avatar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接