Skip to content

Instantly share code, notes, and snippets.

@koko1000ban
Last active August 29, 2015 13:58
Show Gist options
  • Save koko1000ban/9931469 to your computer and use it in GitHub Desktop.
Save koko1000ban/9931469 to your computer and use it in GitHub Desktop.
Nested query in Arel
limit = 200
post_table = Post.arel_table
visibility_ids = PostVisibility.select(:post_id).where(user_id: 1).order(id: :desc).limit(limit).arel.as('t')
inner_query = Arel::Table.new(:tmp).project(:post_id).from(visibility_ids.to_sql)
Post.where(post_table[:is_public].eq(true).or(post_table[:id].in(inner_query))).limit(limit)
select `posts`.* from `posts`
where `posts`.is_public = true or `posts`.id in
(select post_id from (select `post_visibilities`.post_id from `post_visibilities` where `post_visibilities`.user_id = 1
order by `post_visibilities`.id desc LIMIT 200) as t) order by `posts`.id desc LIMIT 200;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment