2014-12-02 24 views
1

用戶可以通過鏈接下載報告,鏈接旁邊有一個文本標誌,指示是否已經下載文件 - 「未讀'警惕。我哈瓦的部分,顯示在報告索引中的單個項目:Ajax調用 - 發送數據並在單個動作中渲染部分 - 兩種渲染方法

<p id="chapter_report_index_item"> 
<%= link_to "#{report.chapter_report_original_filename}", chapter_report_path(report), remote: true %> 
<%unless check_read_status?(report) %>Unread 
<%end%> 
<p> 

在chapter_reports_controller.rb我有 -

def show 
    set_chapter_report 
    set_read_status_true(@chapter_report) 
    send_data @chapter_report.chapter_report.read, filename: @chapter_report.chapter_report_original_filename 
    respond_to do |format| 
    format.js 
    end 
end 

而且在show.js,調用重新渲染此單項目部分 -

$("#chapter_report_index_item").html("<%= j (render(partial: 'index_item', locals: {report: @chapter_report})) %>"); 

你會注意到在視圖中check_read_status方法 - 本質上是,部分顯示時,顯示的想法未讀標誌,如果用戶沒有點擊在下載鏈接上。

我的問題是,我試圖在動作中渲染兩件事:下載和部分。什麼是避免這種技術?

本質上,我想要一個下載按鈕,該按鈕在下載文件時發生變化。

更新

我試圖解決這個問題,雖然一個javascript給助手(按下面的評論)。我的問題是send_file和它的同類是不能作爲application_helper.rb

基本上我已經有了一個jQuery調用部分剛剛包含的下載方法的調用方法 -

<%= report.class.name %> 
<%= report.chapter_report_original_filename %> 
<%= asset_download(report) %> 

在助手 -

def asset_download(object) 
    object.chapter_report_original_filename 
    #send_file(object.chapter_report.read, filename:object.chapter_report_original_filename) 
end 

我已經把電話給.class.name等,看看有什麼可以通過。當我取消了send_file電話,我得到的錯誤 -

ActionView::Template::Error (undefined method `send_file' for #<#<Class:0x0... 

我猜COS的方法是提供給ActionController的不的ActionView。

所以問題是 - 我如何使控制器方法在這種情況下可用?或者我找到另一種方法來做到這一點?

更新2根據以下答案,您可以通過呈現包含通過javascript調用的部分來調用send_file方法。您需要按照this question的方法在助手中提供該方法。

回答

0

你可以在兩個單獨的動作(下載和ajax調用)中分割你的動作,並編寫一些前端(javascript)代碼,監聽下載點擊並觸發第二個調用update_read_status動作的ajax(例如通過jquery )。

+0

嗨,謝謝你。它確實發生在我嘗試從js.erb文件中觸發動作,但當我嘗試在應用程序助手中調用某個方法時,出現「無法識別的方法」錯誤。你知道這個方法嗎? – RADan 2014-12-08 17:14:57

+0

當你得到'無法識別的方法'錯誤時,你到底在做什麼? – 2014-12-09 20:27:22

+0

我只是試圖從js文件中調用erb的方法 - 例如<%j download_item(@object)%> - 其中download_item是應用程序助手中的方法。我現在正在嘗試一種稍微不同的方式 - 我要更新問題。 – RADan 2014-12-10 16:48:37