Rails按类别分组文章

时间:2014-03-04 15:05:50

标签: ruby-on-rails

我是rails的新手,我似乎无法弄清楚为什么我不能按类别名称分组文章。我有一个类别表和一个通过提要加入的文章表。以下是我想要完成的一个例子。

示例:

Sports
  article 1
  article 2
  article 3
Food
  article 1
  article 2
Music
  article 1
  article 2

以下是关联:

class Category < ActiveRecord::Base
  attr_accessible :name

  has_many :feeds
  has_many :articles, through: :feeds
end

class Feed < ActiveRecord::Base
  attr_accessible :account_id, :name, :source, :url, :category_id

  belongs_to :category
  has_many :articles
end

class Article < ActiveRecord::Base    
  attr_accessible :guid, :name, :published_at, :summary, :url, :feed_id

  belongs_to :feed
end

在文章控制器中我有这个:

class ArticlesController < ApplicationController

  def index
    @articles = Article.all
    @article_list = @articles.group_by { |t| t.category.name }
  end
end

在文章视图中:

<% @article_list.each do |category, article_items| %>
  <%= category %>   
  <% article_items.each do |article_item| %>
    <% article_item.name%>         
  <% end %>   
<% end %>

1 个答案:

答案 0 :(得分:2)

您需要在ArticleCategory之间建立关联,以便按照您现在定义的group_by进行操作。您可以使用has_one :through来解决此问题:

class Category < ActiveRecord::Base
  attr_accessible :name

  has_many :feeds
  has_many :articles, through: :feeds
end

class Feed < ActiveRecord::Base
  attr_accessible :account_id, :name, :source, :url, :category_id

  belongs_to :category
  has_many :articles
end

class Article < ActiveRecord::Base    
  attr_accessible :guid, :name, :published_at, :summary, :url, :feed_id

  belongs_to :feed
  has_one :category, :through => :feed
end

获得上述has_one :category, :through => :feed后,您就可以成功@article.category,或者更具体地说@article_list = @articles.group_by { |t| t.category.name }成功。

您还需要更新视图,因为您错过了=

<% @article_list.each do |category, article_items| %>
  <%= category %>   
  <% article_items.each do |article_item| %>
    <%= article_item.name %>       # missing here  
  <% end %>   
<% end %>
相关问题