Skip to content

Instantly share code, notes, and snippets.

@jwo
Created January 2, 2013 19:12
Show Gist options
  • Save jwo/4437011 to your computer and use it in GitHub Desktop.
Save jwo/4437011 to your computer and use it in GitHub Desktop.
Inner Query example in active record

Inspiration: https://gist.github.com/4436444

Resulting Query:

SELECT "orders".* FROM "orders" WHERE "orders"."id" IN (SELECT id FROM "orders" GROUP BY account_id ORDER BY order_date DESC)
class Account < ActiveRecord::Base
attr_accessible :name
has_many :orders
end
class Order < ActiveRecord::Base
belongs_to :account
attr_accessible :amount_in_cents, :order_date
scope :recent_by_account, ->{ where(arel_table[:id].in(
Arel::SqlLiteral.new( Order.group(:account_id).order("order_date DESC").select(:id).to_sql))
)
}
end
require 'test_helper'
class OrderTest < ActiveSupport::TestCase
setup do
Account.create!( name: "the-first")
Account.create!( name: "the-second")
Account.create!( name: "the-third")
Account.all.each do |account|
5.times do |i|
account.orders.create!(amount_in_cents: (100..10000).to_a.sample, order_date: i.days.ago)
end
end
end
test "query should have 1 per account" do
results = Order.recent_by_account
assert_equal 3, results.count
end
end
ActiveRecord::Schema.define(:version => 20130102181052) do
create_table "accounts", :force => true do |t|
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "orders", :force => true do |t|
t.integer "account_id"
t.datetime "order_date"
t.integer "amount_in_cents"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
add_index "orders", ["account_id"], :name => "index_orders_on_account_id"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment