ruby-on-rails – 如何将参数传递给LEFT JOIN?

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 如何将参数传递给LEFT JOIN?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
**修改为更好的可理解性** @H_404_2@**编辑重新命名为文档**

@H_404_2@我想用给定用户的投票记录获取所有用户的文档记录,如果该用户没有投票支持某些文档记录,我仍然希望得到所有的文档记录,而无需投票.
例如:

  1. +------------+--------------+------+
  2. |document.par1|document.par2| vote |
  3. +------------+--------------+------+
  4. | 2 | z | y |
  5. | 3 | w | NULL |
  6. | 4 | x | NULL |
  7. +------------+--------------+------+
@H_404_2@在Ruby on Rails上,如果我尝试这样:

@H_404_2@冷杉试试:

  1. Document.
  2. joins("LEFT JOIN `votes` ON `votes`.`v_id` = `document`.`id` AND `votes`.`giver_id` = ?",user_id).
  3. where('document.creator_id = ?',user_id,.....).
  4. select('votes.*',`document.param1')
@H_404_2@我收到这个错误

  1. RuntimeError in UserDocumentsController#show
  2.  
  3. unknown class: Fixnum
@H_404_2@II.第二尝试:

  1. Document.
  2. joins("LEFT JOIN `votes` ON `votes`.`v_id` = `document`.`id`").
  3. where('document.creator_id = ? AND `votes`.`giver_id` = ?',`document.param1')
@H_404_2@仅返回有投票记录:

  1. +-------------+-------------+------+
  2. |document.par1|document.par2| vote |
  3. +-------------+-------------+------+
  4. | 2 | z | y |
  5. +-------------+-------------+------+
@H_404_2@所以没有2条记录..

@H_404_2@**更新,此解决方案工作**

@H_404_2@III.我的第三个尝试,谢谢你的帮助Mischa:

  1. Document.
  2. joins("LEFT JOIN `votes` ON `votes`.`v_id` = `document`.`id`").
  3. where('document.creator_id = ? AND (`votes`.`giver_id` = ? OR `votes`.`giver_id` IS NULL)',user_id).
  4. select('votes.*',`document.param1')
  5.  
  6. +-------------+-------------+------+
  7. |document.par1|document.par2| vote |
  8. +-------------+-------------+------+
  9. | 2 | z | y |
  10. | 3 | w | NULL |
  11. | 4 | x | NULL |
  12. +-------------+-------------+------+

解决方法

这将为您提供您需要的结果集:
  1. Document.
  2. joins("LEFT JOIN `votes` ON `votes`.`v_id` = `document`.`id`").
  3. where('document.creator_id = ? AND (`votes`.`giver_id` = ? OR `votes`.`giver_id` IS NULL)',`document.param1')

猜你在找的Ruby相关文章