我有一个博客,在同一页面上呈现每个类别及其各自的sub_categories. (索引视图)我有一个导航部分,我想利用它来根据按下的链接只渲染特定的子类别的帖子.我不知道单独使用
ruby是否可行,所以我认为
JQuery可能就是这样.
blog_categories index.html.erb:
<%= link_to "BLOG",blog_path %> <!-- Will render latest posts. --> <li role="presentation" class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false"> NEWS <span class="caret"></span> </a> <ul class="dropdown-menu"> <li role="presentation"><a href="#">All News</a></li> <!-- Will render all subcategories that belong to the "news" category --> <li role="presentation"><a href="#">Good News</a></li> <li role="presentation"><a href="#">Bad News</a></li> </ul> </li> <li role="presentation" class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false"> REVIEWS <span class="caret"></span> </a> <ul class="dropdown-menu"> <li role="presentation"><a href="#">All Reviews</a></li> <li role="presentation"><a href="#">Software</a></li> <li role="presentation"><a href="#">Hardware</a></li> </ul> </li> <% BlogCategory.top_level.find_each do |category| %> <% category.sub_categories.find_each do |sub_category| %> <% sub_category.posts.find_each do |post| %> <%= link_to post do %> ... <% end %> <% end %> <% end %> <% end %>
blog_categories_controller:
def index @category = BlogCategory.find_by_id(params[:id]) unless @category.nil? # Allows for categories to have nothing in them,eliminating the NoMethodError @sub_category = @category.sub_categories.first @posts = @subcategory.posts end end private def cat_params params.require(:blog_category).permit(:name,:parent_id,:sub_category) end
我的sub_categories通过blog_categories表中的parent_id列通过自引用关系与主要类别相关.
我已经阅读了一些有关guides.rubyonrails.org上的活动记录查询的信息,并看到了一些关于Client.where(“orders_count =?”,params [:orders])等条件的问题可以使用吗?
解决方法
查看您的代码和问题,您似乎希望在索引页面上显示所有类别,子类别和每个子类别中的帖子.我假设您的帖子数量有限,否则您可能希望将其限制为每个子类别的n(5?)个帖子数量.如果是这样,您可以拥有以下控制器:
def index @categories = BlogCategory.top_level.includes(sub_categories: :posts) end
然后在视图中,您可以轻松访问@categories,@ category [i] .sub_categories和@categories [i] .sub_categories [j] .posts,而不会从视图中触发任何额外的查询.有点像:
<% @categories.each do |category| %> <li role="presentation" class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false"> <%= category.name %> <span class="caret"></span> </a> <ul class="dropdown-menu"> <% category.sub_categories.each do |sub_category| %> <li role="presentation"><a href="#"><%= sub_category.name %></a></li> <!-- And if you want to show the posts here,then loop through sub_category.posts --> <% end %> </ul> </li> <% end %>
您可以使用jquery显示和隐藏相关的子类别和帖子,具体取决于用户点击的内容.这是一个例子:
http://api.jquery.com/show/