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

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

**编辑重新命名为文档**

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

+------------+--------------+------+
|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

II.第二尝试:

Document.
   joins("LEFT JOIN `votes` ON `votes`.`v_id` = `document`.`id`").
   where('document.creator_id = ? AND `votes`.`giver_id` = ?',`document.param1')

仅返回有投票记录:

+-------------+-------------+------+
|document.par1|document.par2| vote |
+-------------+-------------+------+
|    2        | z           | y    |
+-------------+-------------+------+

所以没有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).
   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')
原文链接:https://www.f2er.com/ruby/272606.html

猜你在找的Ruby相关文章