Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails generate has_many association

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

like image 557
Passionate Engineer Avatar asked Dec 04 '13 06:12

Passionate Engineer


People also ask

How do you create a many-to-many relationship in Rails?

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.

What is the difference between Has_one and Belongs_to?

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.

What is polymorphic association in Rails?

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.

What is self association in Rails?

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.


1 Answers

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.

like image 110
Alex Peachey Avatar answered Oct 10 '22 18:10

Alex Peachey