A belongs_to association sets up a connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model. For example, if your application includes authors and books, and each book can be assigned to exactly one author, you'd declare the book model this way:
class Book < ApplicationRecord
belongs_to :author
end
belongs_to does not ensure reference consistency, so depending on the use case, you might also need to add a database-level foreign key constraint on the reference column, like this:
create_table :books do |t|
t.belongs_to :author, foreign_key: true
end
So belongs_to :author will by default be linked to the Author class.
A has_many association is similar to has_one, but indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a belongs_to association. This association indicates that each instance of the model has zero or more instances of another model. For example, in an application containing authors and books, the author model could be declared like this:
class Author < ApplicationRecord
has_many :books
end
Depending on the use case, it's usually a good idea to create a non-unique index and optionally a foreign key constraint on the author column for the books table:
create_table :books do |t|
t.belongs_to :author, index: true, foreign_key: true
end
with has_many, if you have multiple relationships you will need through.
so this would look like:
class User < ApplicationRecord
has_many :books, through: :book_group
end
I talked about belongs_to and has_many because those are the ones i'm comfortable with at the moment, but there are more relations out there like:
belongs_to
has_one
has_many
has_many :through
has_one :through
has_and_belongs_to_many
Comments