如果您的关联定义如下:
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 %>