Jak*_*ake 8 ruby jquery ruby-on-rails
我有一个博客,在同一页面上呈现每个类别及其各自的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 %>
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
我通过自引用关系通过表中sub_categories的parent_id列与主要类别blog_categories相关.
我已经阅读了一些有关在guides.rubyonrails.org上查询主动记录的信息,并看到了有关条件的信息,例如Client.where("orders_count = ?", params[:orders])可以使用吗?
如果这不是使用HTML下拉菜单迭代BlogCategory的正确方法,我很想知道最好的方法来处理这个问题,谢谢!
这是我发现对我有用的解决方案:
id您可以通过在链接路径中使用相应的(或者slug如果您正在使用它们)来链接到表(在本例中为 blog_categories 表)中的项目。
示例:您想要链接到的子类别具有id“1”(或“评论”),您可以像这样链接到它:
凭身份证:<a href="/blog_category/1">Reviews</a>
与蛞蝓:<a href="/blog/reviews">All Reviews</a>
可以对下拉列表中的所有链接执行此操作:
<li role="presentation" class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">CATEGORIES <span class="caret"></span></a>
<ul class="dropdown-menu">
<!-- without slugs -->
<li role="presentation"><a href="/blog_categories/1">Reviews</a></li>
<li role="presentation"><a href="/blog_categories/2">Tutorials</a></li>
<!-- with slugs -->
<li role="presentation"><a href="/blog/reviews">Reviews</a></li>
<li role="presentation"><a href="/blog/tutorials">Tutorials</a></li>
</ul>
</li>
Run Code Online (Sandbox Code Playgroud)
基本上这些链接的格式是<a href="/[table_name]/[table_item]>Link text</a>
| 归档时间: |
|
| 查看次数: |
623 次 |
| 最近记录: |