A
A
Anton Ivanov2015-10-18 01:09:08
Ruby on Rails
Anton Ivanov, 2015-10-18 01:09:08

Why doesn't unscope work for HABTM in the includes request?

Hi everybody.
There are 2 models.

class User < ActiveRecord::Base
  has_and_belongs_to_many :tasks
  has_and_belongs_to_many :completed_tasks, -> { unscope(where: :completed).where(tasks: {completed: true}) }, class_name: Task, join_table: :users_tasks
end

class Task < ActiveRecord::Base
  default_scope -> { where(completed: false).order(id: :asc) }

  has_and_belongs_to_many :users
end

The code works fine, however the code
User.find(1).completed_tasks
User.includes(:completed_tasks).find(1).completed_tasks

returns nothing. When viewing the log, it is clear that the following conditions are present in the SQL query:
LEFT OUTER JOIN "tasks" ON "tasks"."id" = "users_tasks"."task_id" AND "tasks"."completed" = 'f'
WHERE "tasks"."completed" = 't' AND "users_tasks"."user_id" IN (17)

That is, defalut_scope remains for JOIN tables. How to correctly write unscope for table join?
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question