我从外部API获取大量XML数据。
它为我提供了所有分页数据,每页有20条记录。
它还为我提供了每个文档的总记录数。
我正在使用Typhoeus
gem获取XML -in plist数据,我正在用Plist
gem转换它,我将它们插入到数据库中。
问题是;我可以轻松插入前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
在这里,我正在分析数据:
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。
提前感谢您的帮助。
答案 0 :(得分:1)
我自己解决了这个问题。对于任何可能需要做类似事情的人来说,这是我的解决方案。
def get_videos_from_outer(page=params[:page], kid=params[:kid], totalCount="")
@videos = Video.where(program_id: params[:p_id])
@program = Program.find(params[:p_id])
@fetch = Typhoeus::Request.post("URL", :params => {:commandtype=>"getprogramepisodes", :feedtype=>"plist",:id=>kid.to_i, :page=>page.to_i})
@plist = Plist::parse_xml(@fetch.body.force_encoding 'utf-8')
@totalCount = @plist.second.first['totalCount']
if !totalCount.blank?
@totalCount = totalCount
end
import_outer_videos(@plist, kid, page.to_i, @totalCount.to_i)
end
import_outer_videos
方法。
private
def import_outer_videos(plist, kid, page, totalCount)
@totalCount = totalCount
plist.second.each_with_index do |t, i|
# First page has odd data and here we're getting rid off them
if page.to_i==1
if i > 0
@new = Video.create(:thumb_path=>t['tnPath'], :vid=>t['id'], :title=>t['title'], :type=>t['type'], :kid=>kid, :program_id=>@program.id)
end
else
@new = Video.create(:thumb_path=>t['tnPath'], :vid=>t['id'], :title=>t['title'], :type=>t['type'], :kid=>kid, :program_id=>@program.id)
end
end
if page.to_i < (@totalCount.to_i/20) + 1
page = page.to_i + 1
get_videos_from_outer(page.to_i, kid.to_i, @totalCount)
else
redirect_to :action=>"index", :p_id=>params[:p_id]
end
if @new.errors.blank?
flash[:notice]="#{@totalCount} videos has been transfered."
else
flash[:notice]="No new video."
end
end