Reputation: 11
I have 2 models, Project and TodoItem. Please see below table structures and Models below.
What I am trying to do query all todo_items where assigned = current_user.fullname and completed_at is nil grouped_by project name and Ordered_by the project name.
Then I want to loop out something similar to this:
PROJECT 1 Name
PROJECT 2 Name
Table Structure:
create_table "projects", force: :cascade do |t|
t.string "name"
t.text "details"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "todo_items", force: :cascade do |t|
t.string "content"
t.string "assigned"
t.integer "project_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "completed_at"
end
Models:
class Project < ActiveRecord::Base
has_many :todo_items, :dependent => :destroy
validates_presence_of :name
end
class TodoItem < ActiveRecord::Base
belongs_to :project
end
Thank you in advance.
Upvotes: 0
Views: 50
Reputation: 99
For your complete solution
you can try this
@projects = Project.includes(:todo_items).where(todo_items: {assigned: current_user.fullname, completed_at: nil }).group("projects.name").order("projects.name")
Upvotes: 1
Reputation: 901
You're almost there.
You just need to add .where
:
@projects = Project.includes(:todo_items).where(completed_at: nil)
Upvotes: 0