Skip to content

Instantly share code, notes, and snippets.

@holysugar
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save holysugar/883d472043852bdc9b8d to your computer and use it in GitHub Desktop.
Save holysugar/883d472043852bdc9b8d to your computer and use it in GitHub Desktop.
テンポラリテーブル使うコードたたき台みたいな
require 'active_record'
def temporary_table_class(name, sql = nil, primary_key: nil, &block)
name = name.to_s.tableize
if block
ActiveRecord::Schema.define do
create_table(name, :temporary => true, &block)
end
elsif sql
ActiveRecord::Schema.define do
create_table(name, :temporary => true, as: sql)
end
else
raise "sql or block must be defined"
end
Class.new(ActiveRecord::Base) do
self.table_name = name
self.primary_key = primary_key if primary_key
def self.drop
name = self.table_name
ActiveRecord::Schema.define do
drop_table(name)
end
end
end
end
#__END__
# クラス名はわかりやすさのためにここではARの規約に沿った定数にしているけど
# 実際は一時変数になることを想定している
Item = temporary_table_class(:items) do |t|
t.string :name
t.integer :price
end
100.times{ Item.create(name: %w(a b c d e).sample, price: rand(1..1000)) }
HighPrice = temporary_table_class(:high_prices, "SELECT name, MAX(price) as max_price FROM items GROUP BY name", primary_key: "name")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment