**修改为更好的可理解性**
@H_404_2@**编辑重新命名为文档**
@H_404_2@我想用给定用户的投票记录获取所有用户的文档记录,如果该用户没有投票支持某些文档记录,我仍然希望得到所有的文档记录,而无需投票.
例如:
例如:
@H_404_2@在Ruby on Rails上,如果我尝试这样: @H_404_2@冷杉试试:
- +------------+--------------+------+
- |document.par1|document.par2| vote |
- +------------+--------------+------+
- | 2 | z | y |
- | 3 | w | NULL |
- | 4 | x | NULL |
- +------------+--------------+------+
@H_404_2@我收到这个错误:
- 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')
@H_404_2@II.第二尝试:
- RuntimeError in UserDocumentsController#show
- unknown class: Fixnum
@H_404_2@仅返回有投票记录:
- Document.
- joins("LEFT JOIN `votes` ON `votes`.`v_id` = `document`.`id`").
- where('document.creator_id = ? AND `votes`.`giver_id` = ?',`document.param1')
@H_404_2@所以没有2条记录.. @H_404_2@**更新,此解决方案工作** @H_404_2@III.我的第三个尝试,谢谢你的帮助Mischa:
- +-------------+-------------+------+
- |document.par1|document.par2| vote |
- +-------------+-------------+------+
- | 2 | z | y |
- +-------------+-------------+------+
- 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).
- 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)',`document.param1')