Skip to content

Instantly share code, notes, and snippets.

@brettfishman
Created June 28, 2012 23:29
Show Gist options
  • Save brettfishman/3014703 to your computer and use it in GitHub Desktop.
Save brettfishman/3014703 to your computer and use it in GitHub Desktop.
ActiveRecord 3.2.6 JOIN issue when models are backed by tables in an alternate database
# In an initializer under config/initializers
[OtherPerson, OtherGroup].each do |model|
model.establish_connection(other_database[Rails.env].symbolize_keys!)
end
# Model definitions
class OtherGroup < ActiveRecord::Base
self.table_name = 'groups'
has_many :other_persons, :class_name => "OtherPerson", :foreign_key => 'group_id'
end
class OtherPerson < ActiveRecord::Base
self.table_name = 'persons'
belongs_to :other_group, :foreign_key => 'group_id'
# This method always returns []
def self.find_eligible_people(group)
person_relation = OtherPerson.scoped.
where(:status => "happy").
joins(:other_group).
where(:groups => {:name => group.name})
person_relation
end
# The workaround
def self.find_eligible_people(group)
group_id = OtherGroup.where(:name => group.name).first.id
person_relation = OtherPerson.scoped.
where(:status => "happy").
where(:group_id => group_id)
person_relation
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment