2014-02-18 23 views
-1

我有一個控制器donations_controller渲染中軌與一些變量視圖

class DonationsController < ApplicationController 
    def index 
    donation = Donation.find_by_id(1).donation 
    donation_percent = donation.to_f/50*100 
    end 
end 

和視圖donations/_index.html.erb

<div class="progress"> 
    <div class="bar" style="width:<%[email protected]_percent%>%;"></div> 
</div> 
<p>Donated: &euro;<%[email protected]%></p> 

當我嘗試呈現它的任何其他視圖內(例如,static/index.html.erb - 我的網站主頁),它沒有變量就被渲染。這裏是我使用的代碼

... 
<%=render partial: "donations/index", donation: @donation, donation_percent: @donation_percent%> 
... 

我該怎麼做才能渲染變量?謝謝。

+0

你甲肝e '<%= yield %>' 在您的佈局? –

+0

當然,我有,但它怎麼能幫助我? – enjaku

回答

1

你需要把從控制器要在意見納入實例變量來訪問值,所以:

class DonationsController < ApplicationController 
    def index 
    @donation = Donation.find_by_id(1).donation 
    @donation_percent = @donation.to_f/50*100 
    end 
end 

接下來,你index觀點幾乎是正確的,你通過這些實例變量爲部分當地人(但忘了包起來當地人哈希):

... 
<%=render partial: "donations/index", locals: {donation: @donation, donation_percent: @donation_percent} %> 
... 

但在局部,你應該叫他們爲本地變量

<div class="progress"> 
    <div class="bar" style="width:<%= donation_percent %>%;"></div> 
</div> 
<p>Donated: &euro;<%= donation %></p> 
0

您不必在佈局中手動渲染部分。將<%= yield %>放在應該是部分的位置,Rails將處理選擇併爲當前操作呈現正確的模板。

至於您的原始問題 - 要從另一個模板呈現一個模板,請使用render partial而不是render template

有關更多說明,請參見官方Rails guide

+0

我需要它不在產量內,我需要它作爲佈局的一部分。 – enjaku

1

它不能夠訪問@donation,因爲它沒有被定義爲捐贈#索引操作(假設)以外。

你有兩個選擇 1)要麼你把代碼,無論你要訪問的捐贈

@donation = Donation.find_by_id(1).donation 
@donation_percent = @donation.to_f/50*100 

2)或聲明的部分模板,而不是渲染模板呈現爲局部和重命名你的文件以 '_index.html.haml'

渲染部分: '捐款/指標',捐贈:@donation

變化從@donation變量名捐贈

+0

我已經完成了它,但沒有任何改變,即使我嘗試在任何其他視圖內渲染。根據你的回答我會重寫我的問題。 – enjaku