我試圖做到這一點:在縣無法找到合適的控制器動作來渲染視圖
縣
縣1人名單(鏈接的位置列表1 縣2(鏈接中縣1
位置1中列出郡的地點位置的2 等
名單(鏈接的位置頁 位置2等
我的路線如下:
Rails.application.routes.draw do
resources :counties do
resources :locations
end
root 'home#index'
get "/:county_name_with_prefix" => "counties#show_by_name"
get "/:location_name_with_prefix" => "locations#show_by_name"
end
我CountiesController是這樣的:
class CountiesController < ApplicationController
before_filter :extract_county_name, :only => [:show_by_name]
**before_filter :extract_location_name, :only => [:show_by_name]**
def index
@counties = County.all
@locations = Location.all
end
def show
@county = County.find(params[:id])
@locations = Location.all
end
def show_by_name
@county = County.find_by_name(@county_name)
@locations = Location.all
render :show
end
private
def extract_county_name
@county_name = params[:county_name_with_prefix].gsub(County::ROUTE_PREFIX,"").gsub("-", " ").strip
end
**private
def extract_location_name
@location_name = params[:location_name_with_prefix].gsub(Location::ROUTE_PREFIX,"").gsub("-", " ").strip
end**
end
縣指數的看法是這樣的:
<p>List of all counties</p>
<ul>
<% @counties.each do |county| %>
<li><%= link_to "Locations in #{county.name}", generate_county_url_with_prefix(county) %></li>
<% end %>
</ul>
縣顯示查看是這樣的:
<h1>Domestic Cleaning Services in <%= @county.name %></h1>
<ul>
<% @locations.each do |location|%>
<li><%= link_to "#{location.name}"**,generate_location_url_with_prefix(location) %></li>**
<%end%>
</ul>
我可以得到這個工作,如果我刪除**stars**
之間的代碼。然而,我想不出的是如何獲得鏈接到每個單獨位置頁面的位置列表 - 我的嘗試如**code marked like this**
中所示。根據關係/數據,數據庫表格肯定可以設置好。任何想法大規模歡迎...
LocationsController:
class LocationsController < ApplicationController
before_filter :extract_location_name, :only => [:show_by_name]
def index
@location = Location.all
end
def show
@location = Location.find(params[:id])
end
def show_by_name
@location = Location.find_by_name(@location_name)
render :show
end
private
def extract_location_name
@location_name = params[:location_name_with_prefix].gsub(Location::ROUTE_PREFIX,"").gsub("-", " ").strip
end
end
end
要覆蓋一個通過發送'/:county_name_with_prefix'和'/:location_name_with_prefix'這兩個路由將不起作用,因爲第二個條目將覆蓋首先,因爲你沒有顯示你路由到它的'LocationsController'將很難提供幫助。 – engineersmnky 2014-10-02 20:43:26
@engineersmnky謝謝我已經添加了位置控制器 – user3735114 2014-10-02 21:00:34
這很棒,但您是否注意到我關於重疊路線的其他評論?這個非常重要。 Rails無法區分指定的兩條路線。我會將它們更改爲「get」/ counties /:county_name_with_prefix「=>」counties#show_by_name「和'get」/ locations /:location_name_with_prefix「=>」locations#show_by_name「',這樣它們不會重疊,預期。 – engineersmnky 2014-10-03 15:13:10