Is there a way to generate has_many association for a column using Rails generate scaffold
command in the console?
I know belongs_to
is available and there are use cases of references
but not sure of has_many
In Rails, there are two main ways of creating many-to-many relationships between models: using a has_and_belongs_to_many association. using has_many :through association.
They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.
Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.
Self-referential association is used to associate a model with itself. The most frequent example would be, to manage association between a friend and his follower. ex. rails g model friendship user_id:references friend_id:integer.
There is no column for a has_many
relationship. A belongs_to
is backed by a column which holds a foreign key.
So if you generate a scaffold: rails g scaffold Post
And then you generate another scaffold: rails g scaffold Comment post:references
Then rails will create a migration that adds a column named post_id
to the Comment table and creates an index on it. For both tables, it creates foreign key constraints between comments(post_id)
and posts(id)
. Rails will also add belongs_to :post
in the Comment model.
At anytime you can add a has_many
to a model as long as another model belongs_to
the first model and has a migration with the foreign key column.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With