How to Implement has_many Association in Rails Application?

How to Implement has_many Association in Rails Application?

12 Oct 2021
0 Comments
How to Implement has_many Association in Rails Application?

Overview:

In Rails, The association is a connection between two Active Record models. Why do we need associations between models? Because it makes common operations in your code. For example, Consider a Rails application that includes a model for a category and a model for courses. Each user can have many courses. Then we can use has many associations.
 

The has_many association is a one-to-many relationship with another model. This association implies that one instance of the declared model has many instances of another model, thus the associated model is pluralized. Along with a has_many association, there is usually a belongs_to association with the other model.
 

When you declare a has_many association, the foreign key would be on the same table and model in which you declared your belongs_to association.
 

Steps for implementation:


Step 1: If we have two models Category and Course

Step 2: While creating the model
rails g model Category name:string description:text

rails g model course name description user:references

has many association

Run rails db:migrate

has many association courses
 

Step 3: Goto category.rb
has_many :courses

has many association application
 

And goto course.rb file

write belongs_to :category

has many association app
 

Step 4: Goto go course controller and pass category_id in params

has many association
 

Step 5: goto view page and write

<label>Select Category :</label>

<%= f.collection_select :category_id, Category.order(:name), :id, :name %>

select category
 

Step 6: rails db:migrate

Step 7: Run localhost:3000




Leave a comment: