创建一个目录结构(使用嵌套路由+漂亮的URL,...)

时间:2011-10-19 19:52:06

标签: ruby-on-rails routing friendly-url

我正在开发一个prototyp(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 %>

任何想法为什么会弹出此错误消息?或者一般来说是否有更好的方法?

1 个答案:

答案 0 :(得分:2)

您应该看到的代码部分是:

class Location < ActiveRecord::Base
  belongs_to :states
end

它应该是

class Location < ActiveRecord::Base
  belongs_to :state
end

另一个注意事项,虽然与您所获得的错误无关,但Ruby程序员通常更喜欢array.each而不是for item in array