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

How would you choose betwe...

Câu trả lời

Choosing between belongs_to and has_one in Ruby on Rails depends on the direction of the relationship and where the foreign key is stored. Here’s a detailed explanation to help you understand and decide which one to use:

Understanding the Relationship

  1. belongs_to Association:

    • The belongs_to association is used when the model declaring it contains the foreign key.
    • It indicates that the current model holds a reference to another model.
    • Example: If an Account belongs to a Supplier, the accounts table will have a supplier_id column.
    • Code Example:
      ruby Copy
      class Account < ApplicationRecord
        belongs_to :supplier
      end
  2. has_one Association:

    • The has_one association is used when the other model contains the foreign key.
    • It indicates that the current model is referenced by another model.
    • Example: If a Supplier has one Account, the accounts table will have a supplier_id column.
    • Code Example:
      ruby Copy
      class Supplier < ApplicationRecord
        has_one :account
      end

Key Differences

  • Foreign Key Placement:

    • belongs_to: The foreign key is in the table of the model declaring the belongs_to association.
    • has_one: The foreign key is in the table of the other model.
  • Semantic Meaning:

    • belongs_to: Indicates ownership or a direct reference to another model.
    • has_one: Indicates that another model references this model.

Practical Example

Consider a scenario with Supplier and Account models:

  • A Supplier has one Account.
  • An Account belongs to a Supplier.

The corresponding migrations might look like this:

ruby Copy
class CreateSuppliers < ActiveRecord::Migration[7.1]
  def change
    create_table :suppliers do |t|
      t.string :name
      t.timestamps
    end

    create_table :accounts do |t|...
senior

senior

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

senior

What is Rack?

middle

Can you explain the difference between ActiveSupport’s HashWithIndifferentAccess and Ruby’s Hash ?

junior

How Is Visibility Of Methods Changed In Ruby (encapsulation)?

Bình luận

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

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