如何在ActiveRecord的说明中编写查询

时间:2018-08-14 13:37:02

标签: ruby-on-rails ruby-on-rails-5 rails-activerecord

表格:

posts - id, title, description, vote_count
post_votes - id, user_id, post_id, vote

我的SQL查询:

SELECT posts.*, (select vote from post_votes where post_votes.post_id = posts.id and post_votes.user_id = 1) as my_vote FROM posts;

我是RoR和ActiveRecord的新手。有人可以帮我在ActiveRecord中编写上述查询吗?

我正在使用Rails 5.2

1 个答案:

答案 0 :(得分:0)

我在ActiveRecord中解决了上述查询:

Post.select("posts.*, (select vote from post_votes where post_votes.post_id = posts.id and post_votes.user_id = 1) as my_vote").order('created_at DESC')