gpt4 book ai didi

ruby-on-rails - Ruby on Rail、Carrierwave - 表单验证失败时文件上传字段消失

转载 作者:行者123 更新时间:2023-12-04 13:46:48 29 4
gpt4 key购买 nike

上周我一直在努力解决这个问题。

我有一个 Ruby on Rails 应用程序,它有一个表单提交,其中包含许多文件上传和输入字段。成功提交后,表单信息将保存到 Postgres 数据库,并发送一封包含提交信息和附件的电子邮件。如果我禁用验证或表单未通过任何验证,这将正常工作,但是如果验证失败,则会出现问题。

Fields on Load Documents Selected Missing/Disabled Fields

如果选择了一个文件,然后单击提交按钮,并且表单验证失败,则某些文件字段将被禁用或从 html 中完全删除。它还将重新排列原始字段中的字段。例如,附加文档是upload49,但在验证失败后,文件字段现在是upload25。

我已经尝试了所有我能想到的谷歌搜索来追踪问题。我发现的最接近的是 AJAX 问题,出于安全原因,默认情况下不允许文件上传,这就是为什么需要 Carrierwave。我注意到当错误 'ajax:aborted:file' 发生时,这就是删除文件字段的原因。我发现的另一件事是,当按下提交按钮并且正在处理表单时,所有文件字段都被暂时禁用,我只能假设某处发生了破坏,阻止它们在验证失败时重新启用。

如果我为 'ajax:aborted:file' 添加了一个监听器并让它返回 false,它会阻止文件字段被弄乱,但它会导致表单提交和验证停止工作。

任何帮助将不胜感激。如果您有任何问题或需要更多代码,请告诉我。

下面是一些代码片段。

# uploaders/AttachmentsUpload.rb
class AttachmentsUploader < CarrierWave::Uploader::Base
# Choose what kind of storage to use for this uploader:
# storage :fog
storage :file # for local testing, saving to S3 in production

# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end

# models/buyer_under_contract.rb
class BuyerUnderContract < ApplicationRecord
include AttributeOption
belongs_to :user
belongs_to :team
mount_uploader :upload1, AttachmentsUploader
mount_uploader :upload2, AttachmentsUploader
mount_uploader :upload3, AttachmentsUploader
mount_uploader :upload4, AttachmentsUploader
mount_uploader :upload5, AttachmentsUploader
mount_uploader :upload6, AttachmentsUploader
...
...
mount_uploaders :upload49, AttachmentsUploader

after_create :send_notification

# Agent Info Validations
validates :location, :agent_fname, :agent_lname,
:agent_email,
presence: true
validates :prior_contract,
presence: true,
if: :prior_contract_status?
validates :previous_transaction_coordinator,
presence: true,
if: :previous_contract?
....
....
....

def send_notification
NotificationMailer.buyer_under_contract_form(self).deliver
end
end

# controllers/buyer_under_contracts.rb
class BuyerUnderContractsController < ApplicationController
include ListItemsController
responders :ajax_modal, :collection
respond_to :js, only: %i[index new create edit update]
respond_to :html, only: [:index]
load_and_authorize_resource

before_action :restrict_users, only: %i[new create edit update]

def new
list_item.user = current_user
respond_with(list_item)
end

def create
puts '@create' + list_item.inspect
created = list_item.save

if created
redirect_to URI(request.referer).path
return
end
puts '@errors' + list_item.errors.inspect
respond_with(list_item)
end

def update
updated = list_item.update_attributes(resource_params)

return if resource_params[:_update_type] == 'inline'

if updated
target = URI(request.referer).to_s
redirect_to target
return
end
respond_with(list_item)
end

def buyer_under_contract_params
numeric = %i[location zip mls purchase_price broker_commission_percentage
broker_commission_fee buyer_transaction_fee]

params[:buyer_under_contract].each do |param, value|
if param.to_sym == :communication_pref
value.delete_if { |x| x == '' }
params[:buyer_under_contract][param] = value.join(', ')
end
if param.to_sym == :documents_present
value.delete_if { |x| x == '' }

params[:buyer_under_contract][param] = value.join(', ')
end
next unless numeric.include?(param.to_sym)
params[:buyer_under_contract][param] = value.gsub(/[^0-9.]/, '')
end

# I know this is bad practice, was having problems with
# unpermitted parameters even though I permitted them,
# just for testing now.
params.require(:buyer_under_contract).permit!
end


# views/_form.html.haml
= simple_form_for(@buyer_under_contract, remote: true) do |form|
-if @buyer_under_contract.errors.any?
.modal-header.error-container
-@buyer_under_contract.errors.messages.each do |attr, _msg|
.row
=I18n.t(:"simple_form.labels.buyer_under_contract.#{attr}") + " is required"

.modal-body.container
%div.hidden.container
= form.input :user_id, value: User
%div.agent_info.container
%h2 Agent Information
%div.container
%h3.form *Location
= form.input :location, placeholder:'Location', label:false, collection: Team.all, prompt: 'Location', wrapper_html: {class: 'col-sm-5'}, input_html: { data: { placeholder: 'Location', 'allow-clear': false } }
Select the city your office is located in
%div.container
%h3.form Agent Name (Your Name)
= form.input :agent_fname, label:'First', wrapper_html: { class: 'col-sm-5' }
= form.input :agent_lname, label:'Last', wrapper_html: { class: 'col-sm-5' }
...
...
...
%div.documents.container(id = 'doc_uploads')
%h3.form Documents Upload(s)
%div.container.hidden(id = 'doc_addendum_purchase_agree_arbitration')
%h5 Addendum to Purchase Agreement/Arbitration
= form.file_field :upload1, multiple: false, wrapper_html: { class: 'col-sm-6'}
%div.container.hidden(id = 'doc_addendum_purchase_agree_cic')
%h5 Addendum to Purchase Agreement/CIC (if applies)
= form.file_field :upload2, multiple: false, wrapper_html: { class: 'col-sm-6'}
%div.container.hidden(id = 'doc_addendum_purchase_agree_inspect')
%h5 Addendum to Purchase Agreement/Inspections
= form.file_field :upload3, multiple: false, wrapper_html: { class: 'col-sm-6'}
...
...
%div.container.hidden(id = 'doc_additional')
%h5 Additional Documents
= form.file_field :upload49, multiple: true, wrapper_html: { class: 'col-sm-6'}


.modal-footer
= form.button :submit, class: "btn btn-success contract_submit_button", data: {disable_with: "Please wait…"}, value: 'Submit'
= link_to "Cancel", "#", class: "btn btn-danger", data: {dismiss: "modal"}, type: "button"

# assets/buyer_under_contract.js.coffee
# Some complicated JS to hide and unhide fields, but no
# disabling of fields, I can attach if it's needed

# mailers/notification_mailer.rb
class NotificationMailer < ApplicationMailer
default from: "info@test.com"

def buyer_under_contract_form(submission)
@submission = submission
@user = User.find_by_id(@submission.user_id)
@address = @submission.address
@location = Team.find_by_id(@submission.location)
puts 'address: ' + @address.to_s
puts 'user: ' + @user.to_s
puts 'location: ' + @location.to_s

attachments.inline['white-logo.png'] = File.read('app/assets/images/white-logo.png')
(1..49).to_a.each do |value|
begin
if @submission.send("upload#{value}").is_a?(Array)
@submission.send("upload#{value}").each do |attachment|
file_url = attachment.to_s
next if file_url == ''
puts 'file url: ' + file_url
puts "#{Rails.root}/public/#{file_url}"
attachments.inline[attachment.filename] = File.read("#{Rails.root}/public/#{file_url}")
end
else
file_url = @submission.send("upload#{value}").to_s
next if file_url == ''
puts 'file url: ' + file_url
puts "#{Rails.root}/public/#{file_url}"
attachments.inline[@submission.send("upload#{value}").filename] = File.read("#{Rails.root}/public/#{file_url}")
end
rescue
puts 'Mailer/Attachment Failure'
puts $!.message
next
end
end
mail(to: "testuser@example.com",
subject: "New Buyer Closing File at #{@address} - #{@location}",
reply_to: @user.email
)
end
end

最佳答案

遇到了同样的问题,花了几天时间修复它。但是当我找到解决方案时,我有点失望。

如果您使用 jquery_ujs 而不是 rails-ujs,请尝试在 application.js 中将其更改为 rails-ujs。

可能现在回答为时已晚,但会有其他人遇到同样的问题。

关于ruby-on-rails - Ruby on Rail、Carrierwave - 表单验证失败时文件上传字段消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45134868/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com