article_controller.rb
def index
@articles = Article.all
end
記事/index.html.erb
<% @articles.each do |article| %>
comments in article <%= article.comments.count %>
<% end %>
ネストされたルート (記事内のコメント) は、コメントのルートの作成/破棄に関してより重要です。accepts_nested_attributes_for :comments
また、Article モデルを必ず追加してください。これにより、次のようなことができるようになります。
たとえば、articles_controller.rb で
def show
@article = Article.find(params[:id])
# creates a new comment object with atricle_id already initialized
@comment = @article.comments.build
end
編集
パフォーマンスを気にし始めるなら、キットーのコメントに同意します.
この移行を追加します。
class AddCommentsCountToArtices < ActiveRecord::Migration
def change
add_column :articles, :comments_count, :integer, null: false, default: 0
end
end
Comment モデルの関係宣言を次のように変更します。
belongs_to :article, counter_cache: true
次に、このような呼び出しを行っarticle.comments_count
て、の代わりにカウントを取得できますatricle.comments.count
。また、カウントが 0 の場合は、クエリを作成することさえできないため、すばらしいことです (Rails 3 Way の p. 195)。
counter_cache の仕組みに興味がある場合: コメントが作成または破棄されるたびに、親記事の comments_counter 属性を更新するコールバックを所属するクラス (この場合は Comment クラス) に追加します。
また、 Obie Fernandezがここで説明しているように、counter_cache 機能を既存のデータベースに簡単に追加できます。