Skip to content

Instantly share code, notes, and snippets.

@groman-me
Created May 9, 2012 13:49
Show Gist options
  • Save groman-me/2644618 to your computer and use it in GitHub Desktop.
Save groman-me/2644618 to your computer and use it in GitHub Desktop.
AR#merge
Order.paid.joins(:user).merge(User.blue_eye)
# => SELECT "orders".* FROM "orders" INNER JOIN "users" ON "users"."id" = "orders"."user_id" WHERE "orders"."status" = 3 AND "users"."eye_color" = 'blue' AND "users"."status" = 1
Order.paid.where(:user_id => User.blue_eye.pluck(:id))
# => SELECT id FROM "users" WHERE "users"."eye_color" = 'blue' AND "users"."status" = 1
# => SELECT "orders".* FROM "orders" WHERE "orders"."status" = 3 AND "orders"."user_id" IN (2, 3)
Order.paid.joins(:user).where(:users => { :eye_color => 'blue' })
# => SELECT "orders".* FROM "orders" INNER JOIN "users" ON "users"."id" = "orders"."user_id" WHERE "orders"."status" = 3 AND "users"."eye_color" = 'blue'
class User < ActiveRecord::Base
STATUS = { :visible => 1 }
has_many :orders
scope :blue_eye, where(:eye_color => 'blue', :status => STATUS[:visible])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment