我最近一直在努力教自己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")
这是我在posts控制器中的索引方法的代码:
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'
好像我应该以不同方式处理这些路线?或者不是这种情况,因为类别列是帖子模型的一部分而不是它自己的表格?非常感谢你的帮助!
答案 0 :(得分: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 %>