Ruby on Rails

ActiveRecord Associations

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

24 Interview-Fragen·
Mid-Level
1

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

Antwort

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?

Antwort

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?

Antwort

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 Interview-Fragen

Meistere Ruby on Rails für dein nächstes Interview

Zugang zu allen Fragen, Flashcards, technischen Tests, Code-Review-Übungen und Interview-Simulatoren.

Kostenlos starten