
ActiveRecord Associations
has_many, belongs_to, has_one, has_and_belongs_to_many, polymorphic, dependent destroy
1Which association should be used in a Comment model to indicate that a comment must belong to an article?
Which association should be used in a Comment model to indicate that a comment must belong to an article?
답변
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.
2Which association should be used in an Article model to allow having multiple associated comments?
Which association should be used in an Article model to allow having multiple associated comments?
답변
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.
3Which association should be used for a user to have a single profile, where the profile contains the foreign key?
Which association should be used for a user to have a single profile, where the profile contains the foreign key?
답변
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.
How to model a many-to-many relationship between Post and Tag with a join table containing additional attributes?
What is the default behavior of the dependent: :destroy option on a has_many association?
+21 면접 질문