Skip to content

Instantly share code, notes, and snippets.

@timothyklim
Created December 3, 2012 13:35
Show Gist options
  • Save timothyklim/4195076 to your computer and use it in GitHub Desktop.
Save timothyklim/4195076 to your computer and use it in GitHub Desktop.
Rails and PostgreSQL inheritance
class AwesomeAd < ActiveRecord::Base;end
class CreateAds < ActiveRecord::Migration
def up
create_table "ads", :force => true do |t|
t.decimal "uid", :precision => 30, :scale => 0, :null => false
t.string "title", :null => false
end
create_table :my_cool_ads, options: 'INHERITS (ads)'
create_table :awesome_ads, options: 'INHERITS (ads)'
end
def down
drop_table :awesome_ads
drop_table :my_cool_ads
drop_table :ads
end
end
class MyCoolAd < ActiveRecord::Base;end
example_ids = [1, 2, 3, 4]
initialize_klasses = {}
result = ActiveRecord::Base.connection.execute(
ActiveRecord::Base::sanitize_sql_array[%Q{
SELECT distinct("ads".*), pg_class.relname
FROM ads, pg_class
WHERE ads.id IN (?)
AND ads.tableoid = pg_class.oid
}, example_ids
]).to_a
result.map do |attributes|
object_attributes = attributes.reject { |key, _| key == 'relname' }
klass = attributes['relname']
initialize_klasses[klass] ||= klass.camelize.singularize.constantize
object = initialize_klasses[klass].new object_attributes, without_protection: true
object.instance_variable_set :'@new_record', false
object
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment