** Edited for a better understandability **
** Edit renamed to Document **
I want to get all user Document records with vote records on them by given user, and if that user is not voted for some document records i still want to get all document records without votes. For egzample:
+------------+--------------+------+
|document.par1|document.par2| vote |
+------------+--------------+------+
| 2 | z | y |
| 3 | w | NULL |
| 4 | x | NULL |
+------------+--------------+------+
On Ruby on Rails if i tryed this:
I. firs try:
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')
i got this error:
RuntimeError in UserDocumentsController#show
unknown class: Fixnum
II. second try:
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')
Returns only that records that have votes:
+-------------+-------------+------+
|document.par1|document.par2| vote |
+-------------+-------------+------+
| 2 | z | y |
+-------------+-------------+------+
So there is missing 2 records..
** Updated, this solution works **
III. My third try, thanks for help 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 |
+-------------+-------------+------+
This will get you the result set you need:
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With