如何将参数传递给LEFT JOIN?

时间:2012-11-15 22:39:00

标签: ruby-on-rails ruby

**为了更好的理解而编辑**

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

我希望获得给定用户的所有用户文档记录及其投票记录,如果该用户未投票支持某些文档记录,我仍希望获得所有文档记录而无需投票。 例如:

+------------+--------------+------+
|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` = ?', user_id, user_id, .....).
   select('votes.*', `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, user_id).
   select('votes.*', `document.param1')

+-------------+-------------+------+
|document.par1|document.par2| vote |
+-------------+-------------+------+
|    2        | z           | y    |
|    3        | w           | NULL |
|    4        | x           | NULL |
+-------------+-------------+------+

3 个答案:

答案 0 :(得分:9)

这将为您提供所需的结果集:

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')

答案 1 :(得分:0)

条件子句不应出现在joins

这应该有效:

Myclass.
  joins("LEFT JOIN `votes` ON `votes`.`v_id` = `myclass`.`id`").
  where('myclass.creator_id = ? AND `votes`.`giver_id` = ?', user_id, user_id, .....).
  select('votes.*', `myclass.param1')

答案 2 :(得分:0)

我有同样的问题,但似乎没有工作, 我找到了一种解决方法,通过声明一个字符串变量并将“ON”条件传递给该字符串并在SQL命令中引用它。

例如:on_condition = "(votes.giver_id ="+user_id+")"

命令是:

Myclass.joins("LEFT JOIN votes).on(on_condition).where('myclass.creator_id = ?', user_id).select('votes.*', myclass.param1)