如何下载使用生成器生成的 xml 文件以在 rails 中另存为 xml 文件

How to download xml file generated using builder to save as an xml file in rails

我已经尝试在我的索引控制器中使用以下代码

    def index
      @forms = Form.all
      data = render_to_string( :action => :index )
      send_data data, :filename => "xyz.xml", :disposition => 'attachment'
    end 

但它保存的是对象 ID,而不是 xml 输出的值。

我想保存我可以在 index.xml.builder 中看到的输出

这是index.xml.builder视图


    xml.instruct! :xml, :version => "1.0", :encoding => 'UTF-8'

    @forms.each do |form|
      xml.admin do
        xml.applicant_info do
          xml.id form.form_id
          xml.company_name form.company_name
          xml.submission_description form.submission_description

      form.applicants.each do |applicant|
            xml.applicant_contacts do
              xml.applicant_contact do
                xml.applicant_contact_name applicant.applicant_contact_name, :'applicant-contact-type' => applicant.applicant_contact_type 
                xml.telephones do
                  xml.telephone applicant.telephone, :'telephone-number-type' => applicant.telephone_number_type
                end 
                xml.emails do
                  xml.email applicant.email
                end 
              end
            end
          end
        end
        xml.application_set do
          xml.application_containing_files form.application_containing_files
          xml.application_information do
            xml.application_number form.application_number, :'application-type' => form.application_type 
          end
        end
      end
    end
  end
end

与其在操作视图中编写 xml 生成器,不如在操作视图中使用私有方法编写该代码。

def index
  @forms = Form.all
  send_data build_xml.to_xml, :filename => "xyz.xml", :disposition => 'attachment'
end 

private

def build_xml
  Nokogiri::XML::Builder.new do |xml|
    xml.root do
      @forms.each do |form|
        xml.admin do
          xml.applicant_info do
            xml.id form.form_id
            xml.company_name form.company_name
            xml.submission_description form.submission_description

        form.applicants.each do |applicant|
              xml.applicant_contacts do
                xml.applicant_contact do
                  xml.applicant_contact_name applicant.applicant_contact_name, :'applicant-contact-type' => applicant.applicant_contact_type 
                  xml.telephones do
                    xml.telephone applicant.telephone, :'telephone-number-type' => applicant.telephone_number_type
                  end 
                  xml.emails do
                    xml.email applicant.email
                  end 
                end
              end
            end
          end
          xml.application_set do
            xml.application_containing_files form.application_containing_files
            xml.application_information do
              xml.application_number form.application_number, :'application-type' => form.application_type 
            end
          end
        end
      end
    end
  end
end