我有一个rails 3博客应用程序,其中包含has_many
和belongs_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
答案 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 %>