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:

yaml Copy
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:

ruby Copy
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

entry

Explain what is Ruby on Rails?

expert

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

junior

Explain what is Rails Active Record in Ruby on Rails?

Bình luận

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

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