Ruby on rails 如何将参数传递给左联接?
**为更好理解而编辑** **编辑重命名为文档** 我希望获得给定用户的所有带有投票记录的用户文档记录,如果该用户没有为某些文档记录投票,我仍然希望获得所有没有投票的文档记录。 对于egzample:Ruby on rails 如何将参数传递给左联接?,ruby-on-rails,ruby,Ruby On Rails,Ruby,**为更好理解而编辑** **编辑重命名为文档** 我希望获得给定用户的所有带有投票记录的用户文档记录,如果该用户没有为某些文档记录投票,我仍然希望获得所有没有投票的文档记录。 对于egzample: +------------+--------------+------+ |document.par1|document.par2| vote | +------------+--------------+------+ | 2 | z | y | |
+------------+--------------+------+
|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
二,。第二次尝试:
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条记录。
**更新后,此解决方案有效**
三、 我的第三次尝试,谢谢你的帮助,米沙:
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 |
+-------------+-------------+------+
condition子句不应出现在连接中 这应该起作用:
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')
这将获得所需的结果集:
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')
我也有同样的问题,但似乎不起作用, 我发现了一种解决这个问题的方法,声明一个字符串变量,将“ON”条件传递给这个字符串,并在SQL命令中引用它 例如:
on_condition=“(vows.giver_id=“+user_id+””)
命令是:
Myclass.joins(“左连接投票”).on(在条件下)。其中('Myclass.creator\u id=?',user\u id)。选择('vows.*',Myclass.param1)
什么是…
?您应该将Myclass
重命名为更有意义的名称。好的,重命名为Document,现在看起来更好了。否,这只返回用户已投票的用户记录,但如果用户未对多个记录投票,则不会返回这些记录。这将不适用于外部联接:不工作。我得到以下查询:SELECT documents.*从“文档”左侧加入投票
投票投票可投票的id=文档
其中文档
创建者id
=1和(投票.给予者id=1或投票.给予者id=NULL)而且根本没有返回任何文档。当我删除giver_id=NULL时,我得到了所有有投票权的记录。你应该做的是为NULL,而不是=NULL
。很好,但是为什么activerecord不允许在JOIN子句中进行替换?我认为这是相当标准的SQL实践。这会造成潜在的SQL注入攻击漏洞。如果攻击者可以找到一种方法将字符串放入用户\u id
,他可以对数据库造成与ActiveRecord用户一样大的损害(这很可能是一切)。始终使用(?)在SQL查询中替换值。