2016-11-05 71 views
0

我最近一直試圖教自己RoR。在過去的幾周裏,我一直在研究一些教程,並嘗試在我的應用中添加一些自己的功能。我試圖實現的功能看起來很簡單,但懷疑我的解決方案儘可能安全和優雅。RoR:根據列值選擇某些職位

到目前爲止,用戶可以向該網站提交帖子。該模型由圖像,標題,類別和說明組成。用戶還可以對給定的帖子發表評論(評論包含在另一張表中)。我正在嘗試在導航欄上添加一個允許用戶瀏覽特定類別的下拉菜單。換句話說,索引應該只顯示用戶選擇的類別內的帖子。雖然我的解決方案有效,但我對此感到不滿。這裏是我的導航欄代碼:

%button#menu1.btn.btn-primary.dropdown-toggle{"data-toggle" => "dropdown", :type => "button"} 
    Explore 
    %span.caret 
    %ul.dropdown-menu{"aria-labelledby" => "menu1", :role => "menu"} 
    %li{:role => "presentation"} 
     %a 
     = link_to "All", posts_path(categories: "All") 
    %li{:role => "presentation"} 
     %a 
     = link_to "3D Modeling", posts_path(categories: "3D Modeling") 
    %li{:role => "presentation"} 
     %a 
     = link_to "Design", posts_path(categories: "Design") 
    %li{:role => "presentation"} 
     %a 
     = link_to "Drawing", posts_path(categories: "Drawing") 
    %li{:role => "presentation"} 
     %a 
     = link_to "Photography", posts_path(categories: "Photography") 
    %li{:role => "presentation"} 
     %a 
     = link_to "Printmaking", posts_path(categories: "Printmaking") 
    %li{:role => "presentation"} 
     %a 
     = link_to "Sculpture", posts_path(categories: "Sculpture") 
    %li{:role => "presentation"} 
     %a 
     = link_to "Other", posts_path(categories: "Other") 

這裏是我的崗位控制器索引方法代碼:

if params[:categories] && params[:categories] == "All" 
    @posts = Post.all.order('created_at DESC').page params[:page] 
elsif params[:categories] && params[:categories] == "3D Modeling" 
    @posts = Post.where(category: "3D Modeling").page params[:page] 
elsif params[:categories] && params[:categories] == "Design" 
    @posts = Post.where(category: "Design").page params[:page] 
elsif params[:categories] && params[:categories] == "Drawing" 
    @posts = Post.where(category: "Drawing").page params[:page] 
elsif params[:categories] && params[:categories] == "Photography" 
    @posts = Post.where(category: "Photography").page params[:page] 
elsif params[:categories] && params[:categories] == "Printmaking" 
    @posts = Post.where(category: "Printmaking").page params[:page] 
elsif params[:categories] && params[:categories] == "Sculpture" 
    @posts = Post.where(category: "Sculpture").page params[:page] 
elsif params[:categories] && params[:categories] == "Other" 
    @posts = Post.where(category: "Other").page params[:page] 
end 

最後,這裏是我的路線文件中的代碼:

resources :post do 
    resources :comments do 
end 

root 'posts#index' 

看起來好像我應該以不同的方式處理路線?或者,情況並非如此,因爲類別列是後期模型的一部分,而不是其自己的表格?非常感謝你的幫助!

回答

2

試試這個

if params[:categories].present? 
    @posts = Post.where(category: params[:categories]).page(params[:page]) 
else 
    @posts = Post.all.order('created_at DESC').page(params[:page]) 
end 

與類別中刪除的link_to的類別: 「全部」

<%= link_to "All", posts_path %> 
+0

是的!那就是訣竅。非常感謝您花時間回答。 –