0

I'm building a task list app in rails which allows user to create task lists which contain tasks. I am trying set up filtering so I can display only task lists that have all of it's tasks marked as complete.

Currently:

List model:
class List < ActiveRecord::Base
  belongs_to :user
  has_many :tasks
end
Task model:
class Task < ActiveRecord::Base
  belongs_to :list

  def completed?
    !completed_at.blank?
  end
end

As I understand it, ActiveRecord's .where query method only looks at at that model's fields and it's value (e.g: @lists.where(name: "List Name"))

Does anyone know a way of doing something similar to the pseudo code below:

@completed_lists = @lists.where(list.tasks.completed.count == list.tasks.count)

Thanks

0

2 Answers 2

1

You can use this to load all lists that do not have an uncompleted task:

List.where.not(id: Task.where('completed_at IS NULL').pluck('DISTINCT list_id'))
Sign up to request clarification or add additional context in comments.

3 Comments

It will be provide to GroupingError on postgresql. I tested it on another example :(
Writing group('lists.id, tasks.id') accept query on pg, but i am not sure is that work properly. What you think about this ?
I change my answer
0

Try to use List.all.map{|list| list if list.tasks.completed.count == list.tasks.count}

2 Comments

your solution provides to n+1.
Thanks for the answer, it works great except the result is an array, not an ActiveRecord relation. Is there a way to convert it back to an ActiveRecord Relation?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.