我有一个 Rails 3.2.1 应用程序,其中:
class Article < ActiveRecord::Base
belongs_to :category
class Category < ActiveRecord::Base
has_many :articles
在路线:
resources :categories, :shallow => true do
resources :articles
end
我想在我的 Articles#index 中显示所有类别及其文章列表。在我的文章控制器中:
def index
#Categories
@categories = Category.all
@category = Category.find(params[:category_id]) if params[:category_id].present?
@category_articles = @category.present? ? @category.articles : Article.where("created_at >= ?", Time.now - 3.days).order("views DESC", :limit => 5).offset(1)
@feature_article = @category.present? ? @category.articles : Article.where("created_at >= ?", Time.now - 3.days).order("views DESC").first
end
我的观点(文章#索引)
<% @categories.each do |category| %>
<%= link_to category.name, category %> <!-- category name -->
<%= link_to @feature_article.title, @feature_article %> <!-- feature article -->
<% @category_articles.each do |article| %> <!-- Each category articles -->
<%= link_to article.title, article %>
<% end %>
<% end %>
问题是它列出了所有类别,但似乎不尊重 category_id 参数。在每个类别中,它显示所有文章,而不是每个类别的文章。