Set Up Belongs To
When to Use
Schema Setup
schema.table :posts do
primary :id, Int64, auto_increment: true
column :title, String
timestamps
end
schema.posts.create!
schema.table :comments do
primary :id, Int64, auto_increment: true
column :body, String
column :post_id, Int64, null: false
timestamps
foreign_key [:post_id], references: :posts, references_columns: [:id]
end
schema.comments.create!Define the Relationship
Access the Parent
Create with Parent
Set Foreign Key Directly
Set via Association
Build Associated Parent
Create Associated Parent
Optional Belongs To
Verify It Works
Related
Last updated
Was this helpful?