How To Implement Has_many Association In Rails Application?

Overview: 

In Rails, The affiliation is an association between two Active Record models. For what reason do we really want the relationship between models? Since it makes normal tasks in your code. For instance, Consider a Rails application that incorporates a model for classification and a model for courses. Every client can have many courses. Then, at that point, we can utilize has numerous affiliations. 


The has_many affiliation is a one-to-numerous relationship with another model. This affiliation infers that one case of the proclaimed model has many examples of another model, subsequently, the related model is pluralized. Alongside a has_many relationship, there is typically a belongs_to relationship with the other model. 


At the point when you pronounce a has_many affiliation, the unfamiliar key would be on a similar table and model wherein you announced your belongs_to affiliation. 


Steps for execution: 

Step 1: If we have two models Category and Course 

Step 2: While making the model 


rails g model Category name:string description:text 

rails g model course name portrayal user:references 


has numerous affiliation 

Run rails db:migrate 

has numerous affiliation courses 


Step 3: Goto category.rb 

has_many :courses 

has numerous affiliation application 


Also, goto course.rb document 

compose belongs_to :class 

has numerous affiliation application 


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

has numerous affiliation 


Step 5: goto view page and compose 

<label>Select Category :</label> 

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

select class 


Step 6: rails db:migrate 


Step 7: Run localhost:3000

Comments

Popular posts from this blog

The Most Secure & Fast Digital Contract & E-Signature Solution for Modern Businesses

All-in-One Review Management Platform

What Is Agile Testing - Methodologies?