0
我從外部API獲取一堆XML數據。如何在Rails中將分頁的XML(plist)數據插入到數據庫中?
它給我所有數據分頁,每頁有20條記錄。
它也給我每個文件的總記錄數。
我得到XML -in事實的plist數據 - 與Typhoeus
寶石,我與Plist
寶石轉換它,我將它們插入到數據庫中。
問題是;我可以很容易地插入前20條記錄 - 這意味着第一頁。但是,如何計算每個文檔有多少頁,以及如何動態查詢其他頁?
這是我的控制器和操作。它適用於第一頁,但不適用於其他頁面。
class Admin::VideosController < ApplicationController
def index
@videos = Video.where(program_id: params[:p_id])
@program = Program.find(params[:p_id])
if params[:cmd]=="get_videos_from_outer"
@page=1
@fetch = Typhoeus::Request.post("URL", :params => {:commandtype=>"getprogramepisodes", :feedtype=>"plist",:id=>@program.kid, :page=>@page})
@plist = Plist::parse_xml(@fetch.body.force_encoding 'utf-8')
import_outer_videos(@plist)
redirect_to :action=>"index", :p_id=>params[:p_id]
end
end
end
在這裏,我instering數據:
private
def import_outer_videos(plist)
@total_count = plist.second.first['totalCount']
if !plist.blank?
plist.second.each_with_index do |t, i|
if @page==1
if i > 0
@new = Video.create(:thumb_path=>t['tnPath'], :vid=>t['id'], :title=>t['title'], :type=>t['type'], :kid=>@program.kid, :program_id=>@program.id)
end
else
@new = Video.create(:thumb_path=>t['tnPath'], :vid=>t['id'], :title=>t['title'], :type=>t['type'], :kid=>@program.kid, :program_id=>@program.id)
end
end
@page = @page + 1 unless @page >= @total_count/20 rescue 0
puts "############################### #{@page} - #{@total_count} ###############################"
if @new.errors.blank?
flash[:notice]="Videos has been uploaded."
else
flash[:notice]="No new video."
end
end
end
PS:我使用的MongoDB和Mongoid。
在此先感謝您的幫助。