2

我希望能够将我的 xml 存储到一个临时文件中,然后将其发送到另一个控制器中的另一个方法进行处理。目前它不允许我读取文件,一旦发送,因为它是一个私有方法。

控制器 #1

xml_doc  = Nokogiri::XML(@builder.to_xml)
@tempfile = Tempfile.new('xml')
@tempfile.write(xml_doc)
redirect_to upload_xml_admin_events_path(:file => @tempfile)

控制器 #2

版本 #1

xml = params[:file].read
xmldoc = Nokogiri::XML(xml)

给我这个错误:“文件:0x6ebfb00”的未定义方法“读取”:字符串

版本 #2

xml = params[:file]
xml.open
xmldoc = Nokogiri::XML(xml)

给我这个错误:为“#File:0x6a12bd8”调用私有方法`open':String

4

1 回答 1

0

It seems like you are thinking that params can be objects, which can be forgiven due to Rails magic. In reality all params are strings with a key in the key=value format.

So the issue here is that when you redirect with the parameter 'file', it turns your Tempfile object into a string. This is why the error is telling you that there are no accessible methods called read or open for a string. I see a few options:

  1. Do whatever you are going to do with the file on Controller 1 instead of redirecting to Controller 2. You won't have to create extra objects, hit a database, or have crazy parameters in your URL.

  2. If the XML can be really large, it might be better to make an AR object called XmlFile or something and write it to the database in Controller 1, then redirect with that id in the parameters. This way, you won't have to send crazy long XML strings in the URL (which is bad):

    # Controller 1
    @xml = XmlFile.new(@builder.to_xml)
    redirect_to upload_xml_admin_events_path(:xml => @xml) #implicitly @xml.to_s
    
    # Controller 2
    @xml = XmlFile.find(params[:xml])
    Nokogiri::XML(@xml)
    
  3. If the XML is always (very) small, you can send the XML as a param in plain text (this seems to be closest to what you are currently doing, but strikes me as less elegant) You might run into URL encoding issues here though.

    # Controller 1
    xml = @builder.to_xml
    redirect_to upload_xml_admin_events_path(:xml => xml)
    
    # Controller 2
    @xml = Nokogiri::XML(params[:xml])
    
于 2013-01-23T22:28:16.640 回答