Comment with belongs_to :post. What behavior does this association provide?The belongs_to association in Rails sets up a one-to-one connection where the model with belongs_to holds the foreign key. This lets you call comment.post to get the associated post.
OrderItem that belongs to Order?The correct syntax uses a symbol for the association name in singular form: belongs_to :order. Using a string or plural form is incorrect.
comment.post raise an error?class Comment < ApplicationRecord
belongs_to :post
endclass Post < ApplicationRecord
endAnd the database has a
comments table without a post_id column. What error will occur when calling comment.post and why?The belongs_to association expects a foreign key column named post_id in the comments table. Without it, Rails cannot find the attribute and raises ActiveModel::MissingAttributeError.
comment.post.title after creation?class Post < ApplicationRecord
has_many :comments
end
class Comment < ApplicationRecord
belongs_to :post
endAnd this code runs:
post = Post.create(title: 'Hello World')
comment = Comment.create(post: post, content: 'Nice post!')What will
comment.post.title return?The comment.post returns the associated post object. Accessing title on it returns the string 'Hello World' that was set when creating the post.
belongs_to association is declared on the model that holds the foreign key column. Why is this necessary?The belongs_to association tells Rails which foreign key column to use to find the related record. This foreign key lives in the model's own table, so the association must be declared there.