Note that there are some explanatory texts on larger screens.

plurals
  1. POnewbie: performing queries on collection of results
    text
    copied!<p>I have two models: projects and todos. In the projects index, I want to show an overview of projects, consisting of the project name and the number of todo items in the project with status "do", "doing", or "done". (eg: do:12 | doing:2 | done:25 ). In my projects controller, i can retrieve all projects, but i additionally need to find out how many todo items with each status are involved in each project. I have fixed this by defining additional database queries in the project index view:</p> <pre><code>Todo.where("project_id = ?", project.id).where("status = ?", "done").count) </code></pre> <p>This does not seem the right (MVC) way to solve this. What would be a better way? How can i perform additional queries on subsets of a collection of results.</p> <p>I have tried to include all relevant code below:</p> <pre><code>class Project &lt; ActiveRecord::Base has_many :todos, dependent: :destroy end class Todo &lt; ActiveRecord::Base acts_as_list belongs_to :project end </code></pre> <p>The schema for the models are:</p> <pre><code>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 </code></pre> <p>the projects controller:</p> <pre><code>class ProjectsController &lt; ApplicationController before_action :set_project, only: [:show, :edit, :update, :destroy] def index @projects = Project.all end </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload