我有一个Article
,每个Article
完全一个User
而为零或一个 ArticleVote
我的代码是:
@articles = Article
.eager_load(:user)
.eager_load(:article_vote)
.where(article_votes: { user_id: session[:user_id]})
.order(created_at: :desc)
产生以下SQL:
SELECT
`articles`.`article_id` AS t0_r0,
`articles`.`user_id` AS t0_r1,
`users`.`user_id` AS t1_r0,
`article_votes`.`article_vote_id` AS t2_r0,
`article_votes`.`article_id` AS t2_r1,
`article_votes`.`user_id` AS t2_r2
FROM `articles`
LEFT OUTER JOIN `users` ON `users`.`user_id` = `articles`.`user_id`
LEFT OUTER JOIN `article_votes` ON `article_votes`.`article_id` = `articles`.`article_id`
WHERE `article_votes`.`user_id` = 1
ORDER BY `articles`.`created_at` DESC
此查询的问题是如果不存在投票(有时它赢了),则不会返回任何记录。我真正需要的是这个(注意哪里已经消失,条件被移到左边的连接处):
SELECT
`articles`.`article_id` AS t0_r0,
`articles`.`user_id` AS t0_r1,
`users`.`user_id` AS t1_r0,
`article_votes`.`article_vote_id` AS t2_r0,
`article_votes`.`article_id` AS t2_r1,
`article_votes`.`user_id` AS t2_r2
FROM `articles`
LEFT OUTER JOIN `users` ON `users`.`user_id` = `articles`.`user_id`
LEFT OUTER JOIN `article_votes` ON `article_votes`.`article_id` = `articles`.`article_id` and `article_votes`.`user_id` = 1
ORDER BY `articles`.`created_at` DESC
我在文档中看到我可以做类似的事情:
has_one :article_vote, -> { where(user_id: 1) }
哪个会将它放在左边的连接中,而不是在哪里,但是这不允许我在查询时指定user_id
,这使得它不可行。
可以这样做吗?