Skip to main content
Ask A Question
You’re not receiving notifications from this thread.

ruby on rails nested model relationship and routes

Rails • Asked by Qasem Hajizadeh

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

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 30,005+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.