belongs to
suggest changeA belongs_to association sets up a one-to-one connection with another model, so each instance of the declaring model belongs to one instance of the other model. In Rails 5 and later, the association is required by default. Pass optional: true to allow a missing parent.
For example, if your application includes users and posts, and each post can be assigned to exactly one user, you’d declare the post model this way:
class Post < ApplicationRecord
belongs_to :user
end
In your table structure you might then have
create_table "posts", force: :cascade do |t|
t.integer "user_id", limit: 4
end
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents