6

確定,所以我在應用控制器中的輔助方法:渲染從是helper_method局部

def run_test(test_name) 
    #computation stuff 
    render :partial => test_name 
end 

我調用它像這樣在的觀點:

<%= run_test("testpartial") %> 

和它呈現確定只有1(儘管...渲染部分似乎是返回一個數組而不是部分內容?),但是如果我將run_test助手調用放入視圖中兩次,我會得到一個雙重渲染錯誤,這不應該發生在partial中。

任何想法?

+0

紅寶石哪個版本和鐵軌你使用,我不運行3.1時得到這種行爲? –

+0

3.1。我正在使用RC候選人,但我升級只是爲了確保它仍然無法正常工作。 – Msencenb

+0

嗯...所以原來我在application_controller中使用helper_method定義了這個幫助器方法:run_test但是將它移動到helpers文件夾中的application_helper文件中工作。所以..我理解了應用程序控制器中定義的助手和助手文件中定義的助手之間的區別。任何人都可以填補我? – Msencenb

回答

6

render在控制器中與在視圖中的render是不同的方法。控制器最終在視圖上調用render,但控制器的render方法本身只能調用一次。它看起來像這樣:

# Check for double render errors and set the content_type after rendering. 
def render(*args) #:nodoc: 
    raise ::AbstractController::DoubleRenderError if response_body 
    super 
    self.content_type ||= Mime[formats.first].to_s 
    response_body 
end 

請注意如果多次調用它會如何引發?

當你調用helper_method你給視圖的代理到控制器的版本render,這是不打算以同樣的方式被用作ActionView的,這,不像控制器,預計被稱爲重複渲染部分和什麼。

-2

你可以嘗試使用render_to_string方法在視圖助手

render_to_string :partial => test_name, :layout => false 
+4

render_to_string在視圖助手中不可用。 –

5

貌似對Rails 3.2這只是工作:

# application_helper.rb 
def render_my_partial 
    render "my_partial" 
end 
+1

這也適用於Rails 3.0。這看起來對我來說是最好的答案。 – sockmonk

+1

我不得不在部分名爲「_my_partial.html.erb」上使用渲染「my_partial.html.erb」,但這工作。 –

+0

問題是如何在由控制器的'helper_method'暴露的控制器上的方法中呈現部分。這並沒有解決這個問題。 – numbers1311407