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)
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 |