Câu hỏi phỏng vấn Ruby on Rails
Câu hỏi

How To Use Two Databases ...

Câu trả lời

Using two databases in a single Ruby on Rails application can be achieved by configuring multiple database connections. This is useful for scenarios where you need to separate different types of data or interact with legacy systems. Here’s a step-by-step guide on how to set this up:

Step-by-Step Guide

1. Configure Database Connections

First, you need to define the connections in your config/database.yml file. Here’s an example configuration:

default: &default
  adapter: postgresql
  encoding: unicode
  pool: 5

development:
  primary:
    <<: *default
    database: primary_db

  secondary:
    <<: *default
    database: secondary_db

test:
  primary:
    <<: *default
    database: primary_db_test

  secondary:
    <<: *default
    database: secondary_db_test

production:
  primary:
    <<: *default
    database: primary_db_production

  secondary:
    <<: *default
    database: secondary_db_production

2. Establish Connections in Models

Next, you need to tell your models which database to use. By default, models use the primary database. For models that should use the secondary database, you can specify the connection like this:

class SecondaryBase < ApplicationRecord
  self.abstract_class = true
  connects_to database: { writing: :secondary, reading: :secondary }
end

class SecondaryModel < SecondaryBase
  # Your model code here
end

3. Migrations for Multiple Databases

Rails supports running migrations for multiple databases. You can specify which database to ...

expert

expert

Gợi ý câu hỏi phỏng vấn

expert

Node.js vs Ruby on Rails. Which would you choose?

senior

How Many Types Of Callbacks Available In RoR?

senior

What Is The Difference Between Save And Save! ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào