如何输出特定类别

时间:2013-03-28 13:10:56

标签: ruby ruby-on-rails-3 blogs

我有一个rails 3博客应用程序,其中包含has_manybelongs_to association中的文章和类别,我有很多类别,如体育新闻,娱乐新闻等,但我希望我的观点只有sportnews到show,我的意思是那些有运动类别的文章,我希望它在我的application.html.erb上显示

class Category < ActiveRecord::Base
  has_many :registrations
  has_one  :payment
  attr_accessible :content, :name, :image, :description

   mount_uploader :image, ImageUploader

end

1 个答案:

答案 0 :(得分:0)

如果您的关联定义如下:

class Category < ActiveRecord::Base
  has_many :articles
end

class Article < ActiveRecord::Base
  belongs_to :category
end

然后获取所有“sportnews”文章就像:(这会进入你的控制器)

class SomeController < ApplicationController
  def index
    @sportnews_category = Category.where(name: "sportnews").first
    @sportnews_articles = @sportnews_category.articles
  end
end

或:

@sportnews_category = Category.where(name: "sportnews").first
@sportnews_articles = Article.where(category_id: @sportnews_category)

您甚至可以定义范围:

class Article < ActiveRecord::Base
  belongs_to :category
  scope :sportnews, includes(:category).where(category: {name: "sportnews"})
end

@sportnews_articles = Article.sportnews

然后在index.html.erb视图中显示:

<% @sportnews_articles.each do |article| %>
  <h1><%= article.title %></h1>
  <p><%= article.content %></p>
<% end %>