Spectator6
Spectator6

Reputation: 403

How do you use url params for creating a link_to when belongs_to and has_many associations are at play?

This is a very simple concept that, even after completing several tutorials, now that I'm "on my own", I can't seem to get the routes/controllers set up properly to return what I'm needing.

The user is presented with a list of states and, upon clicking a state, I want him/her to be taken to a list of counties for that state.

I have models for State and County.

class State < ApplicationRecord
  has_many :counties

class County < ApplicationRecord
  belongs_to :state

Relevant parts of the schema

States:

create_table "states", force: :cascade do |t|
  t.string "name"
  t.string "abbreviation"
  ...

Counties:

create_table "counties", force: :cascade do |t|
  t.string "name"
  t.integer "state_id"
  ...

In my routes, to represent the association, I have nested the following

resources :states, shallow: true do
  resources :counties do
    ...

This seems to be the pertinent portion form rails routes

state_counties  GET  /states/:state_id/counties(.:format)  counties#index

The controller files are currently the standard CRUD actions that come with scaffolds. I've modified the Counties index action to mirror what I use in the console to pull up the needed counties

class CountiesController < ApplicationController

  def index
    @counties = County.where(state_id: params[:id])
  end

In the index.html.erb file for States I'm trying to iterate through the states and provide a link that takes the user to a separate page listing that state's counties and this is where I'm at a loss.

<% states.each do |state| %>
  <%= link_to ... ??? %>

I've tried many different things and I can't get it to take.

When I hard-type the url as say states/3/counties the page renders, but it's blank and no counties are shown even though the log window shows controller: counties, action: index, state_id: '3'.

My thinking so far is that it needs to be a link that refers to the Counties controller and somehow uses the id param for the state that's clicked on... I've scoured through a bunch of different posts, but if there is an answer for this already out there that I missed, please don't hesitate to share it!

Thank you in advance for your help, let me know if I need to post more code snippets. In the meantime, I'll keep digging and update if I come across anything that works.

Upvotes: 0

Views: 82

Answers (1)

idej
idej

Reputation: 5734

To access to index page you should pass state as path attribute:

<%= link_to 'name', state_counties_path(state) %>

rake routes says that state_counties route is /states/:state_id/counties(.:format). It means that state.id is params[:state_id] in counties controller. Change index method in controller to:

@counties = County.where(state_id: params[:state_id])

Upvotes: 1

Related Questions