简体   繁体   中英

I have one category. How print all articles of subcategories without additional gems? Rails

Here is my code. I take testing category one -- nevermind please.

  // Controller
  @categories = Category.find(1).subcategories # Works exellent
  @articles = []
  @categories.each do |category|
     @articles[category.id] = category.articles
  end

  // View
  <% @categories.each do |category| %>
      <h2><%= category.title %></h2>
      <ul>
          <% @articles[category.id].each do |article| %>
             <li><a href="<%= article.slug %>"><%= article.title %></a></li>
          <% end %>
      </ul>
  <% end %>

Here is my output (where 'vel', 'in', 'sit' -- subcategories names):

vel
[nil, nil, nil, nil, nil, nil, #<ActiveRecord::Associations::CollectionProxy []>, #<ActiveRecord::Associations::CollectionProxy []>, #<ActiveRecord::Associations::CollectionProxy []>]
in
[nil, nil, nil, nil, nil, nil, #<ActiveRecord::Associations::CollectionProxy []>, #<ActiveRecord::Associations::CollectionProxy []>, #<ActiveRecord::Associations::CollectionProxy []>]
sit
[nil, nil, nil, nil, nil, nil, #<ActiveRecord::Associations::CollectionProxy []>, #<ActiveRecord::Associations::CollectionProxy []>, #<ActiveRecord::Associations::CollectionProxy []>] 

I have correct work associations:

Catogory:

has_many :articles
has_many :subcategories
has_one :parent

Article

belongs_to :category

I read lot of documentation and find some helpful gems (awesome_nested_set, ancestry) but wanna know how do it without additional gems

You can write it much cleaner:

# Controller
@categories = Category.find(1).subcategories.includes(:articles)

# View
<% @categories.each do |category| %>
  <h2><%= category.title %></h2>
  <ul>
    <% category.articles.each do |article| %>
      <%= link_to article.title, article.slug %>   # Do you really use slug for url? 
    <% end %>
  </ul>
<% end %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM