Subqueries in activerecord

Rails now does this by default ๐Ÿ™‚ Message.where(user_id: Profile.select(“user_id”).where(gender: ‘m’)) will produce the following SQL SELECT “messages”.* FROM “messages” WHERE “messages”.”user_id” IN (SELECT user_id FROM “profiles” WHERE “profiles”.”gender” = ‘m’) (the version number that “now” refers to is most likely 3.2)

ActiveRecord Arel OR condition

ActiveRecord queries are ActiveRecord::Relation objects (which maddeningly do not support or), not Arel objects (which do). [ UPDATE: as of Rails 5, “or” is supported in ActiveRecord::Relation; see https://stackoverflow.com/a/33248299/190135 ] But luckily, their where method accepts ARel query objects. So if User < ActiveRecord::Base… users = User.arel_table query = User.where(users[:kind].eq(‘admin’).or(users[:kind].eq(‘author’))) query.to_sql now shows the reassuring: … Read more

Rails where condition using NOT NIL

Rails 4+ ActiveRecord 4.0 and above adds where.not so you can do this: Foo.includes(:bar).where.not(‘bars.id’ => nil) Foo.includes(:bar).where.not(bars: { id: nil }) When working with scopes between tables, I prefer to leverage merge so that I can use existing scopes more easily. Foo.includes(:bar).merge(Bar.where.not(id: nil)) Also, since includes does not always choose a join strategy, you should … Read more