2011-05-30 69 views
0

我想這樣做一個小白:將多個參數傳遞給ruby ==操作符的正確方法是什麼?

<% if @page[:title] == "Portraits" %> 
     <%= render :partial => "/shared/slideshow" %> 
    <% elsif @page[:title] == "Escapes" %> 
     <%= render :partial => "/shared/slideshow" %> 
    <% elsif @page[:title] == "Articulos pa Web" %> 
     <%= render :partial => "/shared/slideshow" %> 
    <% end %> 

必須有這樣做一個簡潔的方式,但我就是想不通。

+0

謝謝,沒有意識到這是我忽略的東西。完全是無意的。 – 2011-06-06 15:46:13

回答

4

避免將當前擁有的邏輯放在視圖中。

def get_partial_to_render 
    if ["Portraits","Escapes","Articulos pa Web"].include? @page[:title] 
    "shared/slideshow" 
    else 
    "some_other_template" 
    end 
end 
#Note that the partial should not have a leading `/` in the path to it. 

而且在你看來:

把它放進一個輔助方法來代替,並在視圖中使用它

<%= render :partial => get_partial_to_render %> 


或者,如果你不想如果名稱不在數組中,則呈現部分:

def render_my_partial? 
    ["Portraits","Escapes","Articulos pa Web"].include? @page[:title] 
end 

<%= render :partial => "shared/slideshow" if render_my_partial? %> 

請注意,?是方法名稱的一部分。 Ruby不是很棒嗎? :D

2
<% if ["Portraits", "Escapes", "Articulos pa Web"].include?(@page[:title]) %> 
    <%= render :partial => "/shared/slideshow" %> 
<% end %> 
+0

是的,但您應該儘可能避免將這種邏輯放在視圖中。 – Zabba 2011-05-30 22:52:22

相關問題