簡體   English   中英

Rails 5-以js或其他格式(例如PDF)呈現表單提交結果

[英]Rails 5 - Rendering form submission results as js or some other format (e.g. PDF)

我正在嘗試建立一個采用一組條件的表單,使用這些條件運行查詢,並在表單下方的瀏覽器窗口中顯示結果(通過js)或在pdf中使用pdf顯示(通過Prawn)新窗戶。

index.html.erb(表單):

<%= form_for :criteria, url: results_path, method: :patch, remote: true do |f| %>
  ...input fields...
  <%= button_tag("View", remote: true, value: 'js', name: 'format' %>
  <%= button_tag("PDF", remote: true, value: 'pdf', name: 'format', formtarget: '_blank') %>
  <div id='report-results'>
  </div>
<% end %>

控制器:

def index
end

def results
  @results = ...the query...
  respond_to do |format|
    format.js
    format.pdf do
      report = ResultsPdf.new(@results)
      send_data report.render, filename: "Results_#{Date.today}.pdf", type: 'application/pdf', disposition: "inline"
    end
  end
end

results.js.erb:

$('div#report-results').empty();
$('div#report-results').html("<%= escape_javascript(render 'report_results') %>");

使用此代碼,“查看”選項可以工作(在瀏覽器中顯示結果),但“ PDF”選項似乎不起作用。 服務器顯示它以PDF格式命中控制器,運行查詢並發送數據,但pdf本身未生成。 如果我從表單聲明中刪除remote: true ,則PDF選項有效,但View選項僅在瀏覽器中呈現result.js.erb的文本。

這是我如何使它工作的(無論如何,現在):

從表單中刪除了PDF按鈕,迫使用戶通過ajax提交表單並在瀏覽器中查看結果。

report_results部分中添加了一個鏈接,並將在步驟1中運行所產生的記錄的ID作為參數傳遞回:

<%= link_to "PDF", results_path(ids: @results.ids, format: 'pdf'), class: "btn", target: "_blank" %>

向控制器添加了一個if / else塊,以確定對操作的請求是否來自表單提交或pdf鏈接:

if params[:criteria]  
  @results = ...query based on params[:criteria]...  
elsif params[:ids]  
  @results = ...query based on params[:ids]...  
else  
  ...error handling...  
end

哈基? 大概。 它行得通嗎? 是的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM