Sample Rails application for demonstrating Rails 7 - Associations across databases with disable_joins
-
Ruby version: 2.7.1
-
Rails version: 7.0.0
- Clone the application on your local
git clone https://github.com/sampatbadhe/multi-db-app.git
- cd to the
passwordless-authentication-apiapplication directory
cd multi-db-app
- Run
bundlecommand to install all gems
bundle install
-
Configure your
database.ymlfile. -
Run
bundle exec rails db:create -
Run
bundle exec rails db:migrate -
Run
bundle exec rails db:seed. The sample data would be then loaded into application database. -
Run the rails console using
bundle exec rails consoleorbundle exec rails c -
Run following operations and observe the queries.
-
Without
disable_joinsoptionWe would have to add custom methods, as has_many :through/has_one :through associations won't work across databases.
# Set the user > user = User.find_by(email: 'luke@example.com') # Fetch the messages of all the events of a user > user.event_messages # Fetch the latest message on the latest event of a user > user.latest_event_message
-
With
disable_joinsoption# Set the user > user = User.find_by(email: 'luke@example.com') # We can use `has_many :through` association to fetch the messages of all the events of a user > user.messages # We can use `has_one :through` association to fetch the latest message on the latest event of a user > user.latest_message
-