** 为更好理解而编辑**
** 编辑重命名为文档 **
我想获取给定用户的所有带有投票记录的用户文档记录,如果该用户未对某些文档记录进行投票,我仍然希望获取所有没有投票的文档记录。 例如:
+------------+--------------+------+
|document.par1|document.par2| vote |
+------------+--------------+------+
| 2 | z | y |
| 3 | w | NULL |
| 4 | x | NULL |
+------------+--------------+------+
如果我尝试在 Ruby on Rails 上:
我。第一次尝试:
Document.
joins("LEFT JOIN `votes` ON `votes`.`v_id` = `document`.`id` AND `votes`.`giver_id` = ?", user_id).
where('document.creator_id = ?', user_id, .....).
select('votes.*', `document.param1')
我得到了这个错误:
RuntimeError in UserDocumentsController#show
unknown class: Fixnum
二。第二次尝试:
Document.
joins("LEFT JOIN `votes` ON `votes`.`v_id` = `document`.`id`").
where('document.creator_id = ? AND `votes`.`giver_id` = ?', user_id, user_id, .....).
select('votes.*', `document.param1')
仅返回有投票的记录:
+-------------+-------------+------+
|document.par1|document.par2| vote |
+-------------+-------------+------+
| 2 | z | y |
+-------------+-------------+------+
所以少了2条记录..
** 已更新,此解决方案有效 **
三。我的第三次尝试,感谢 Mischa 的帮助:
Document.
joins("LEFT JOIN `votes` ON `votes`.`v_id` = `document`.`id`").
where('document.creator_id = ? AND (`votes`.`giver_id` = ? OR `votes`.`giver_id` IS NULL)', user_id, user_id).
select('votes.*', `document.param1')
+-------------+-------------+------+
|document.par1|document.par2| vote |
+-------------+-------------+------+
| 2 | z | y |
| 3 | w | NULL |
| 4 | x | NULL |
+-------------+-------------+------+
最佳答案
这将为您提供所需的结果集:
Document.
joins("LEFT JOIN `votes` ON `votes`.`v_id` = `document`.`id`").
where('document.creator_id = ? AND (`votes`.`giver_id` = ? OR `votes`.`giver_id` IS NULL)', user_id, user_id).
select('votes.*', `document.param1')
关于ruby-on-rails - 如何将参数传递给 LEFT JOIN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13407489/