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

标签 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

二。第二次尝试:

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条记录..

** 已更新,此解决方案有效 **

三。我的第三次尝试,感谢 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 |
+-------------+-------------+------+

最佳答案

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

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

关于ruby-on-rails - 如何将参数传递给 LEFT JOIN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13407489/

相关文章:

javascript - Rails 下使用 webpacker 进行 Bootstrap-notify 返回 $.notify 不是一个函数

ruby-on-rails - 带有 accepts_the_nested_attributes 的 belongs_to 不在对象中保存外键

python - Django 相当于 Rails 的 x.days.from_now

ruby-on-rails - 为什么我的 rails3 beta4 模型中出现 "SystemStackError: stack level too deep"

ruby-on-rails - cURL无法连接到本地主机,但浏览器可以

javascript - 无法在 Capybara 测试的拆卸方法中执行 localStorage.clear

ruby-on-rails - 测试 rails 中 delayed_job 插件的优先级

ruby-on-rails - 为什么 ActiveRecord 有时只是自动提供相互关联?

ruby 正则表达式删除额外\n

ruby-on-rails - 为什么在安装 Rails 时出现 "write permission"错误?