【发布时间】:2017-08-31 00:24:25
【问题描述】:
在设计用户编辑个人资料页面中,我想添加一个名为“添加验证文档”的自定义字段,该字段包含使用回形针 gem 上传的所有文档并且必须更新。用户可以上传多个文档。
verification_document.rb
class VerificationDocument < ActiveRecord::Base
belongs_to :user
has_attached_file :verification_documents
validates_attachment_content_type :verification_documents, {:content_type => %w( application/pdf )}
end
用户.rb
class User < ActiveRecord::Base
has_many :verification_documents
end
在views/devise/registrations/edit.html.erb中
<div class="row">
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: {method: :put}, multipart: true) do |f| %>
<div class="form-group">
<%= f.text_field :fullname, autofocus: true, placeholder: "Full Name *", class: "form-control" %>
</div>
<div class="form-group">
<%= f.email_field :email, placeholder: "Email *", class: "form-control" %>
</div>
<span class="btn btn-default btn-file btn-green pad_small">Upload Verification Documents
<input type="file" accept="application/pdf" name="input-file-preview"/>
<%= file_field_tag "verification_documents[]", type: :file, multiple: true %>
</span>
<div class="actions">
<%= f.button "Save", class: "btn btn-green pad_small" %>
</div>
routes.rb
devise_for :users,
path: '',
path_names: {sign_in: 'login', sign_out: 'logout',sign_up: 'sign-up', edit: 'profile'},
controllers: {
omniauth_callbacks: 'omniauth_callbacks',
registrations: 'registrations'
}
如何在 RegistrationsController
def update
if @user.update(user_params)
if params[:verification_documents]
params[:verification_documents].each do |doc|
@user.verification_documents.create(verification_documents: doc)
end
end
redirect_to root_path, notice: "Updated..."
else
render :edit
end
如何在设计用户编辑操作期间同时上传多个验证文档?
注意:我已经使用回形针 gem 在设计用户表中成功上传了一个验证文档。但是我想上传多个验证文档并在用户个人资料视图页面中显示所有文档。
我在 ApplicationController 中为单个文档上传添加了以下几行:
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:fullname, :subscribe])
devise_parameter_sanitizer.permit(:account_update, keys: [:fullname, :reset_password_token, :verification_documents])
end
我的要求与 Rails Devise - Register User with Associated Model , 但是这里我想在更新设计用户的同时将多个验证验证文档上传到verification_documents模型而不是地址属性。
非常感谢任何帮助。在此先感谢!
【问题讨论】:
-
在用户模型中使用 accepts_nested_attributes_for 并在您的 registrations/edit.html.erb 文件中使用 fields_for 上传多个文件。请参考stackoverflow.com/questions/13506735/…
-
多文件上传使用需要使用嵌套形式 ref:stackoverflow.com/questions/24597721/…
标签: ruby-on-rails ruby ruby-on-rails-4 devise