How to Implement has_many Association in Rails Application?

How to Implement has_many Association in Rails Application?

24 Sep 2022
How to Implement has_many Association in Rails Application?


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 an 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

Run rails db:migrate

Step 3: Goto category.rb

And goto course.rb file

write belongs_to :category

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

Step 5: goto view page and write

<label>Select Category :</label>

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

Step 6: rails db:migrate

Step 7: Run localhost:3000

Leave a comment: