【问题标题】:how to output a specific category如何输出特定类别
【发布时间】:2013-03-28 13:10:55
【问题描述】:

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

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

   mount_uploader :image, ImageUploader

end

【问题讨论】:

  • 拜托我的问题中的代码与我想要的不同,我只是使用它,所以 stackoverflow 可以让我发布
  • “我的问题中的代码与我想要的不同,我只是使用它,所以 stackoverflow 可以让我发布”?失败!显示与您的问题相关的代码。使用不相关的代码有什么意义,有什么好处?

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


【解决方案1】:

如果您的关联定义如下:

class Category < ActiveRecord::Base
  has_many :articles
end

class Article < ActiveRecord::Base
  belongs_to :category
end

然后获取所有“体育新闻”文章就这么简单:(进入您的控制器)

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 %>

【讨论】:

  • @OnozorObogbareAlex 我添加了视图部分
  • 不,我已经定义了我希望它在我的视图中显示的范围,我也不想限制为 5(感谢 stefan)
  • 只需添加limit(5),例如Article.sportnews.limit(5)
  • 顺便说一句,所有这些主题都包含在Ruby on Rails Guides
  • 我正在为 nil:NilClass 获取未定义的方法 `each'
猜你喜欢
  • 2021-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-14
  • 1970-01-01
  • 2023-02-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多