I am working on a prototyp (rails 2.2.2) to create a similiar page structure as the business directory from http://www.redbeacon.com/s/b/.
Goal should be to have the following paths: mysite.com/d/state/location/ …which displays an index of something. So far, I did the following…
Controllers and models:
$ ruby script/generate controller Directories index show
$ ruby script/generate controller States index show
$ ruby script/generate controller Locations index show
$ ruby script/generate model State name:string abbreviation:string
$ ruby script/generate model Location name:string code:string state_id:integer
$ rake db:migrate
routes:
map.states '/d', :controller => 'states', :action => 'index'
map.locations '/d/:state', :controller => 'locations', :action => 'index'
map.directories '/d/:state/:location', :controller => 'directories', :action => 'index'
…built in the models the relations:
class State < ActiveRecord::Base
has_many :locations
end
class Location < ActiveRecord::Base
belongs_to :states
end
…added actions to the controllers:
class StatesController < ApplicationController
def index
@all_states = State.find(:all)
end
end
class LocationsController < ApplicationController
def index
@all_locations = Location.find(:all)
@location = Location.find_by_id(params[:id])
end
end
class DirectoriesController < ApplicationController
def index
@location = Location.find_by_id(params[:id])
@all_tradesmen = User.find(:all)
end
end
The States Index View
<h1>States#index</h1>
<p>Find me in app/views/states/index.html.erb</p>
<br><br>
<% for state in @all_states %>
<%= link_to state.name, locations_path(state.abbreviation.downcase) %>
<% end %>
The Locations Index View
<h1>Locations#index</h1>
<p>Find me in app/views/locations/index.html.erb</p>
<br><br>
<% for location in @all_locations %>
<%= link_to location.name, directories_path(location.state.abbreviation, location.name) %>
<% end %>
But I am stuck, I get the following error message:
NoMethodError in Locations#index
Showing app/views/locations/index.html.erb where line #6 raised:
undefined method `state' for #<Location:0x104725920>
Extracted source (around line #6):
3: <br><br>
4:
5: <% for location in @all_locations %>
6: <%= link_to location.name, directories_path(location.state.abbreviation, location.name) %>
7: <% end %>
Any Ideas why this error message pops up? Or generally any ideas for a better approach?
The part of the code you should look at is:
and it should be
Another note, although not related to the error you are getting, Ruby programmers usually prefer
array.eachthanfor item in array.