2011-11-25 39 views
2

在Post模型中,我有一個屬性,如「content_type」。不同類型的帖子應該以不同的方式顯示在同一個列表中。現在我只有一個想法做到這一點:不同類型的內容的不同部分

<%= 
     @posts.each do |d| 
      if d.content_type == "NormalStory" 
       render :partial => 'posts/normal', :locals => { :content => d } 
      elsif d.content_type == "FotoStory" 
       render :partial => 'posts/foto', :locals => { :content => d} 
      elsif d.content_type "VideoStory" 
       render :partial => 'posts/video', :locals => { :content => d } 
      end 
     end 
    %> 

你能推薦我更'優雅'的東西嗎?

回答

4

我會創造出活用了一個幫手部分來自content_type,類似於:

def render_post(post) 
    template = post.content_type.sub(/Story$/, '').downcase 
    render :partial => "posts/#{template}", :locals => { :content => post } 
end 
+1

我第二種方法。您基本上爲「content_type」值和部分名稱設置約定,因此您可以添加更多類型而無需觸摸代碼。其他答案都需要您在添加新內容類型時編輯代碼。雖然,在編寫一個輔助方法之前,我會查看一下'ActionController :: Responder'(http://api.rubyonrails.org/classes/ActionController/Responder.html)。 – David

1

你可以嘗試這樣的:

<%= 
@posts.each do |d| 
if d.content_type == "NormalStory" 
     view_name = "normal" 
elsif d.content_type == "FotoStory" 
     view_name = "foto" 
elsif d.content_type "VideoStory" 
     view_name = "video" 
end 
render :partial => "posts/"+view_name, :locals => { :content => d } 
end 
%> 
2
<% @posts.each do |d| %> 
<%= render :partial => get_path(d.content_type), :locals => { :content => d } %> 
<% end %> 

在助手(應用程序/傭工/)你應該定義這個輔助方法

def get_path(content_type) 
    case content_type 
    when "NormalStory" 
     'posts/normal' 
    when "FotoStory" 
     'posts/foto' 
    when "VideoStory" 
     'posts/video' 
    end 
end 
相關問題