I'm attempting to follow the Rails Docs and Railscast#88 but with 3 models. The page will have 3 drop down boxes for State, County, & City. I have State > County working with JQuery. But when trying to build the grouped_collecion_select for the City things are breaking down.
Here are the 3 models:
service_area_state.rb
class ServiceAreaState < ActiveRecord::Base
has_many :service_area_counties
default_scope -> { order(name: :asc) }
end
service_area_county.rb
class ServiceAreaCounty < ActiveRecord::Base
belongs_to :service_area_state
default_scope -> { order(name: :asc) }
end
service_area_city.rb
class ServiceAreaCity < ActiveRecord::Base
belongs_to :service_area_county
end
In my controller, I have the following:
def index
@states = ServiceAreaState.all
@counties = ServiceAreaCounty.all
@cities = ServiceAreaCity.all
end #index
In the view I have:
index.html.erb
<div class="row">
<div class="field" id='state_div'>
<%= label_tag :service_area_state_id, "State", id:"service_area_state" %> <br/>
**This works**
<%= collection_select(:service_area_state, :id, @states, :id, :name, prompt: true ) %>
</div>
<div class="field" id='county_div'>
<%= label_tag :service_area_county_id, "County" %><br>
**This works**
<%= grouped_collection_select(:service_area_county, :service_area_county_id, @states, :service_area_counties, :name, :id, :name, prompt: true ) %>
</div>
<div class="field" id='city_div'>
<%= label_tag :service_area_city_id, "City" %><br>
**This does not work**
<%= grouped_collection_select(:service_area_city, :service_area_county_id, @counties, :service_area_cities, :name, :id, :name, prompt: true ) %>
</div>
</div>
I get the following error:
undefined method `service_area_cities' for #<ServiceAreaCounty:0x007fb5e7dac060>
On this line:
<%= grouped_collection_select(:service_area_city, :service_area_county_id, @counties, :service_area_cities, :name, :id, :name, prompt: true ) %>
Can someone spot where I went wrong?
Thanks!
You need to set up service_area_cities as an association in the ServiceAreaCounty model (sounds like it is a has_many association):
class ServiceAreaCounty < ActiveRecord::Base
belongs_to :service_area_state
has_many :service_area_cities
default_scope -> { order(name: :asc) }
end