Created
December 3, 2012 13:35
-
-
Save timothyklim/4195076 to your computer and use it in GitHub Desktop.
Rails and PostgreSQL inheritance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AwesomeAd < ActiveRecord::Base;end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyCoolAd < ActiveRecord::Base;end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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