我有名为User
,的模型Activity
,Task
并且我可以执行以下操作
> 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
但是当我尝试merge
这两个时,我得到一个数组:
> puts Activity.joins(:task).merge(User.first.shared_tasks).to_sql
NoMethodError: undefined method `to_sql' for []:Array
为什么不返回关系?我需要在其上放置一个 where 子句。
更新:
经过进一步检查,它似乎User.first.shared_tasks
正在立即被评估为一系列任务。order
我可以通过添加调用来获得我想要的行为:
> 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
除了添加一个空之外,还有更好的方法来防止该关系被评估order
吗?