プロジェクトと todos の 2 つのモデルがあります。プロジェクト インデックスでは、プロジェクトの概要を、プロジェクト名と、プロジェクト内の「実行中」、「実行中」、または「完了」ステータスの Todo アイテムの数で構成して表示したいと考えています。(例: do:12 | doing:2 | done:25 )。私のプロジェクト コントローラーでは、すべてのプロジェクトを取得できますが、さらに、各プロジェクトに関連する各ステータスの Todo アイテムの数を調べる必要があります。プロジェクト インデックス ビューで追加のデータベース クエリを定義することで、これを修正しました。
Todo.where("project_id = ?", project.id).where("status = ?", "done").count)
これは、これを解決する正しい (MVC) 方法ではないようです。より良い方法は何でしょうか?結果のコレクションのサブセットに対して追加のクエリを実行するにはどうすればよいですか?
以下に関連するすべてのコードを含めようとしました。
class Project < ActiveRecord::Base
has_many :todos, dependent: :destroy
end
class Todo < ActiveRecord::Base
acts_as_list
belongs_to :project
end
モデルのスキーマは次のとおりです。
create_table "projects", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "todos", force: true do |t|
t.string "name"
t.string "description"
t.string "status"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "position"
t.integer "project_id"
end
プロジェクト コントローラー:
class ProjectsController < ApplicationController
before_action :set_project, only: [:show, :edit, :update, :destroy]
def index
@projects = Project.all
end