我已经尝试在我的索引控制器中使用以下代码
def index
@forms = Form.all
data = render_to_string( :action => :index )
send_data data, :filename => "xyz.xml", :disposition => 'attachment'
end
但它正在保存对象 ID,而不是带有值的 XML 输出。
我想保存我可以在视图中的索引.xml.builder中看到的输出
这是索引.xml.生成器视图
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