Ruby on Rails

ActiveRecord Associations

has_many, belongs_to, has_one, has_and_belongs_to_many, polymorphic, dependent destroy

24 câu hỏi phỏng vấn·
Mid-Level
1

Which association should be used in a Comment model to indicate that a comment must belong to an article?

Câu trả lời

The belongs_to association is used to define a relationship where a record belongs to another. In this case, a Comment belongs to an Article. By convention, this implies that the comments table contains an article_id column which is a foreign key to the articles table.

2

Which association should be used in an Article model to allow having multiple associated comments?

Câu trả lời

The has_many association defines a one-to-many relationship. An Article can have multiple Comments. This association is the mirror of belongs_to and does not store a foreign key in its own table, but expects the associated model (Comment) to have an article_id column.

3

Which association should be used for a user to have a single profile, where the profile contains the foreign key?

Câu trả lời

The has_one association defines a one-to-one relationship where the other model contains the foreign key. In the case User has_one :profile, the profiles table will contain a user_id column. This is the inverse of has_one/belongs_to depending on where the foreign key is located.

4

How to model a many-to-many relationship between Post and Tag with a join table containing additional attributes?

5

What is the default behavior of the dependent: :destroy option on a has_many association?

+21 câu hỏi phỏng vấn

Nắm vững Ruby on Rails cho lần phỏng vấn tiếp theo

Truy cập tất cả câu hỏi, flashcards, bài kiểm tra kỹ thuật, bài tập code review và mô phỏng phỏng vấn.

Bắt đầu miễn phí