создать структуру каталогов (с вложенными маршрутами + красивые URL, ...) - PullRequest
1 голос
/ 19 октября 2011

Я работаю над прототипом (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 Ответ

2 голосов
/ 20 октября 2011

Часть кода, на которую вы должны обратить внимание:

class Location < ActiveRecord::Base
  belongs_to :states
end

и она должна быть

class Location < ActiveRecord::Base
  belongs_to :state
end

Еще одно примечание, хотя и не связанное с ошибкой, которую вы получаете, Rubyпрограммисты обычно предпочитают array.each, чем for item in array.

...