I am having issues with my Rails 3.1 app. I have two controllers & models, named counties/county and towns/town.
The county model has has_many :towns and the town model has belongs_to :county.
I am trying to show the County name on the Towns index page to show the title as ‘Towns in -county-name-‘. However, when I put %h1 Towns in #{@towns.county.name} I get a undefined method 'county' error.
The towns controller for index is
def index
@towns = Town.all
end
For the county controller:
def index
@counties = County.all
end
My routes.rb is
resources :counties, :path => "/locations" do
resources :towns, :path => "/"
end
What am I doing wrong?
EDIT: Using this in my towns/index view and it shows the town.county.id and town.county.name:
- @towns.each do |town|
%tr
%td= town.county.id
%td= town.county.name
%td= town.name
%td= town.description
%td= town.slug
I had a similar problem with states and countries (vs town and counties).
For your town migration, did you have an integer to reference the county (see county_id below)
Then in your app/views/town/index.html.erb you can do a County.find