I have models called User, Activity, and Task and I can do the following
> puts Activity.joins(:task).to_sql
SELECT "activities".* FROM "activities" INNER JOIN "tasks" ON "tasks"."id" = "activities"."task_id" ORDER BY date DESC
> puts User.first.shared_tasks.to_sql
SELECT "tasks".* FROM "tasks" INNER JOIN "user_tasks" ON "tasks"."id" = "user_tasks"."task_id" WHERE "user_tasks"."user_id" = 1
But when I try to merge the two, I get an array:
> puts Activity.joins(:task).merge(User.first.shared_tasks).to_sql
NoMethodError: undefined method `to_sql' for []:Array
Why is that not returning a relation? I need to put a where clause on it.
Update:
Upon further inspection, it looks likes User.first.shared_tasks is being evaluated to an array of tasks immediately. I can gett the behavior I want by adding an order call:
> puts Activity.joins(:task).merge(User.first.shared_tasks.order()).to_sql
SELECT "activities".* FROM "activities" INNER JOIN "tasks" ON "tasks"."id" = "activities"."task_id" INNER JOIN "user_tasks" ON "tasks"."id" = "user_tasks"."task_id" WHERE "user_tasks"."user_id" = 1 ORDER BY date DESC
Is there a better way to prevent that relation from being evaluated besides adding an empty order?
Alright, I still have not figured out why
User.first.shared_tasksis being immediately evaluated, but I have figured out a work around. I can just callscoped:Now when I try to do the merge:
It uses
ActiveRecord::Relation#mergeinstead ofArray#merge