** 为更好理解而编辑 **
** 编辑重命名为 Document **
我想获取给定用户的所有带有投票记录的用户文档记录,如果该用户没有为某些文档记录投票,我仍然希望获得所有没有投票的文档记录。例如:
+------------+--------------+------+
|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 |
+-------------+-------------+------+