Skip to content

Instantly share code, notes, and snippets.

@shterrett
Created July 31, 2015 17:03
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 shterrett/51800818ef64c66627e5 to your computer and use it in GitHub Desktop.
Save shterrett/51800818ef64c66627e5 to your computer and use it in GitHub Desktop.
# database.yml
# development:
# database: development
# secondary_development:
# database: second_development
module Second
class Property < ActiveRecord::Base
establish_connection YAML::load(File.open(Rails.root.join('config', 'database.yml')))['second_development']
has_and_belongs_to_many :property_groups
end
end
module Second
class PropertyGroup < ActiveRecord::Base
establish_connection YAML::load(File.open(Rails.root.join('config', 'database.yml')))['second_development']
has_and_belongs_to_many: properties
end
end
# in Rails console
property = Property.first
property_group = PropertyGroup.first
property.property_groups.include? property_group #=> false
property.property_groups.append(property_group)
property.property_groups.include? property_group #=> true
property.reload.property_groups.include? property_group #=> false
# The above implies that the record is not getting saved properly,
# but that the save is not failing
# https://github.com/rails/rails/blob/1883f37742b976d3d20e0ba4a3564911f4868172/activerecord/lib/active_record/associations/collection_proxy.rb#L35
association = property.property_groups.instance_variable_get(:@association)
# https://github.com/rails/rails/blob/1883f37742b976d3d20e0ba4a3564911f4868172/activerecord/lib/active_record/associations/has_many_through_association.rb#L63
join_record = association.send(:build_through_record, property_group)
association.class.connection #=> a database connection with the database name "development"
property.class.connection #=> a database connection with the database name "second_development"
property_group.class.connection #=> #a database connection with the database name "second_development"
# In development, there is also a join table (with the same name). The thrust of the project is to
# eventually unify the databases. This is why the write isn't failing, but also isn't showing
# up on read. It's writing to development, but reading from second_development
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment