All threads / ruby on rails nested model relationship and routes

Ask A Question


You’re not receiving notifications from this thread.

ruby on rails nested model relationship and routes

Qasem Hajizadeh asked in Rails

I have these models: Sport, Country, League and Match
Also I do have SportsController, CountriesController, LeaguesController and MatchsController

So the question is:
1: how i can set relation between models ?
2: how i can set routs like this



Note : all of the countries don't have all sports for example Soccer Sport exist in all countries but volleyball exist in some countries

For 1. have a look at many-to-many relationship. With Rails this can be done like follows:
has_many: :country_sports
has_many: sports, through: :country_sports

has_many :country_sports
has_many :sports, through: :country_sports

belongs_to :sport
belongs_to :country

The last model is the one that connects the Sport and Country model and for the bare minimum only need country_id and sport_id.

For 2, you can nest the routes like follows:
resources :sports do
resources :country do
resources :leagues do
resources :matches

This is the gist of it, so feel free if you have specific issues with this.

Chris, it would be really great to see a video on how to set up nested routes properly. I have looked at every tutorial online, and nothing makes sense :D

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 33,665+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.