некоторое время назад, Я написал веб-приложение с использованием RoR v.3.2.13 ... все было проверено и работает правильно в течение некоторого времени. .. сейчас, я собираюсь обновить всю среду до рельсов 4.2.5! Я нашел много проблем, улучшающих структуру, все было решено почти легко найти множество предложений в Интернете!ruby on rails веб-сервис не работает после обновления до рельсов 4.x
последняя дают мне еще несколько неприятностей ...
хорошо, я необходимость загружать поток .xml из пальмового устройства на сервер, чтобы обновить несколько записей базы данных ....
это пример .xml поток мобильный терминал посылает на сервер:
<?xml version="1.0" encoding="utf-8"?>
<readings>
<reading>
<opercode>a001a</opercode>
<barcode>000073680</barcode>
<opid>4</opid>
<datetime>2012-01-22T00:07:34+01:00</datetime>
</reading>
<reading>
<opercode>a001a</opercode>
<barcode>000073679</barcode>
<opid>4</opid>
<datetime>2012-01-22T00:07:38+01:00</datetime>
</reading>
</readings>
, как вы можете видеть, она содержит bounch показаний, содержащих четыре поля каждых.
в случае беспроводное соединение не работает, я уже построил представление, содержащее форму HTML и поле загрузки файла ....
контроллер принимает поток, используя те же действия, как вы можете видеть здесь:
.........................
#
# receives the readings stream and passes it to the parser
def upload
#
# different part of code if request is from .html o .xml
respond_to do |format|
# the request is from .html page
format.html do
# checks the uploaded file 'content type'
if params[:readings_file].instance_variable_get(:@content_type) == "text/xml"
# the file is .xml
# identifies the readings operator_id
operator_id = Operator.find_by_code(params[:readings_file].instance_variable_get(:@original_filename)[0..4]).id
# retrieves the number of readings stored into .xml file
original_filename = params[:readings_file].instance_variable_get(:@original_filename).partition(".")[0]
expected_readings = original_filename.partition("-P-")[2].to_i != 0 ? original_filename.partition("-P-")[2].to_i : original_filename.partition("--")[2].to_i
# binds the temporary file for nokogiri parsing
temp_file = File.open(params[:readings_file].instance_variable_get(:@tempfile))
readings_to_be_loaded = Nokogiri::XML(temp_file)
# parses the readings records
result = parse_xml(readings_to_be_loaded, operator_id)
# checks parsing result against expected readings count
if result != expected_readings
message = "WARNING - Inside .xml " + expected_readings.to_s + " records was present, only " + result.to_s + " has been accepted as valid readings!!"
else
message = "OK - .xml stream succesfully parsed!"
end
else
# the file is not .xml
message = "ERROR - Invalid readings file format detected --> 'not xml'!!"
end
logger.debug message
redirect_to readings_path, :flash => {:message => message} and return
end
#
# the request is from .xml stream
format.xml do
if params[:readings].present?
# determines the number of expected readings inside the stream and retrieves the operator code
if params[:readings][:reading][0].nil?
expected_readings = 1
oper_code = params[:readings][:reading][:opercode]
else
expected_readings = params[:readings][:reading].count
oper_code = params[:readings][:reading][0][:opercode]
end
# initializes the good readings counter
readings_count = 0
........
omissis
........
else
# the stream don't contains readings, return the http error code 406 -> 'Not Acceptable'
logger.debug "ERROR - Readings file content is incorrectly formatted!!"
render nothing: true, status: 406 and return
end
end
end
# not .xml request nor html upload
# nothing has been processed, ingores the upload and returns status code 404 -> 'resource not found'
logger.debug "ERROR - Incorrect data stream content"
render :nothing => true, status: 404 and return
end
................
затем дифференцировать действия, если поток данных был загружен из HTML в файл или непосредственно в виде XML-потока.
теперь если я загрузить файл, используя вид HTML, все работает отлично (как рельсы 3,2 или 4,2 работает правильно и разбор чтение) ....
имитировать действия по прямой загрузке .xml с использованием консоль на терминале, я использую эту команду:
curl -v -H "Content-Type: application/xml; charset=utf-8" --data-ascii @a001a-12115-81843-P-5.xml http://localhost:3000/readings/upload.xml
, если поток загружается непосредственно с помощью XML-формата ... рельсов 3.2 работает нормально, рельсы 4.2 возвращает «406 Не приемлем» (см извлеченных журналов строка!)
журнал из рельсов 3.2:
Started POST "/readings/upload.xml" for 127.0.0.1 at 2015-01-22 21:32:35 +0100
Processing by ReadingsController#upload as XML
Parameters: {"readings"=>{"reading"=>[{"opercode"=>"a001a", "barcode"=>"000073685", "opid"=>"4", "datetime"=>"2015-01-21T20:18:20+01:00"}, {"opercode"=>"a001a", "barcode"=>"000073683", "opid"=>"4", "datetime"=>"2015-01-21T20:18:24+01:00"}, {"opercode"=>"a001a", "barcode"=>"000073682", "opid"=>"4", "datetime"=>"2015-01-21T20:18:28+01:00"}, {"opercode"=>"a001a", "barcode"=>"000073679", "opid"=>"4", "datetime"=>"2015-01-21T20:18:36+01:00"}, {"opercode"=>"a001a", "barcode"=>"000073683", "opid"=>"4", "datetime"=>"2015-01-21T20:18:41+01:00"}]}}
Rendered text template (0.0ms)
Completed 200 OK in 49ms (Views: 48.2ms | ActiveRecord: 0.0ms)
бревно из рельсов 4.2:
Started POST "/readings/upload.xml" for 127.0.0.1 at 2016-05-27 21:11:38 +0200
Processing by ReadingsController#upload as XML
ERROR - Readings file content is incorrectly formatted!!
Rendered text template (0.0ms)
Completed 406 Not Acceptable in 2ms (Views: 0.2ms | ActiveRecord: 0.0ms)
похоже параметры не доходя действие контроллера на всех !! (я предполагаю, что это из-за какого-то ограничения на 4.2 версии фреймворка, но я не смог найти какую-либо конкретную информацию, подтверждающие или опровергающие мои подозреваемые)
PLS Примечание: если я пытаюсь отправить поток непосредственно с помощью пальмовое устройство, я получаю тот же ответ !!
любое предложение хорошо принят,
много заранее спасибо вам всем ... Francesco