2011-10-19 28 views
1

我正在製作一個原型(rails 2.2.2)以創建一個類似於http://www.redbeacon.com/s/b/的業務目錄的頁面結構。創建一個目錄結構(嵌套路線+漂亮的網址,...)

目標應該是具有以下路徑:mysite.com/d/state/location/ ...其中顯示的東西的索引。到目前爲止,我做了以下...

控制器和模型:

$ 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 

路線:

map.states '/d', :controller => 'states', :action => 'index' 
map.locations '/d/:state', :controller => 'locations', :action => 'index' 
map.directories '/d/:state/:location', :controller => 'directories', :action => 'index' 

...建在模型中的關係:

class State < ActiveRecord::Base 
    has_many :locations 
end 

class Location < ActiveRecord::Base 
    belongs_to :states 
end 

...向控制器添加操作:

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 

各國指數查看

<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 %> 

的位置索引視圖

<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 %> 

但我堅持,我收到以下錯誤信息:

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 %> 

任何想法,爲什麼這個錯誤消息彈出?或者通常有更好方法的想法?

+0

我知道這是與你的問題相切,但我真的建議不要使用2.2.2之前的Rails有任何其他選擇。如果你正在對此進行原型設計,那聽起來就像你剛從新開始。如果3.0系列對你來說仍然太新,我至少會試着去2.3.11。 – Emily

+0

這是一個現有的系統......但我需要早晚升級到rails 3,這是肯定的。 – hebe

回答

2

代碼的一部分,你應該看的是:

class Location < ActiveRecord::Base 
    belongs_to :states 
end 

,它應該是

class Location < ActiveRecord::Base 
    belongs_to :state 
end 

另注,雖然沒有涉及到你所得到的錯誤,Ruby程序員通常喜歡array.eachfor item in array

+0

很好,謝謝! – hebe