liu*_*tis 13 ruby ruby-on-rails
**编辑以便更好地理解**
**编辑重命名为文档**
我希望获得给定用户的所有用户文档记录及其投票记录,如果该用户未投票支持某些文档记录,我仍希望获得所有文档记录而无需投票.例如:
+------------+--------------+------+
|document.par1|document.par2| vote |
+------------+--------------+------+
| 2 | z | y |
| 3 | w | NULL |
| 4 | x | NULL |
+------------+--------------+------+
Run Code Online (Sandbox Code Playgroud)
在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')
Run Code Online (Sandbox Code Playgroud)
我收到了这个错误:
RuntimeError in UserDocumentsController#show
unknown class: Fixnum
Run Code Online (Sandbox Code Playgroud)
II.第二次尝试:
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')
Run Code Online (Sandbox Code Playgroud)
仅返回有投票的记录:
+-------------+-------------+------+
|document.par1|document.par2| vote |
+-------------+-------------+------+
| 2 | z | y |
+-------------+-------------+------+
Run Code Online (Sandbox Code Playgroud)
所以缺少2条记录..
**更新,此解决方案有效**
III.我的第三次尝试,感谢您帮助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 |
+-------------+-------------+------+
Run Code Online (Sandbox Code Playgroud)
这将为您提供所需的结果集:
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')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6284 次 |
最近记录: |