【发布时间】:2014-10-02 20:12:23
【问题描述】:
我正在尝试这样做:
县列表
县 1(指向县 1 内位置列表的链接 县 2(链接到县 2 内的位置列表 等等
县 1 内的地点列表
位置 1(到位置页面的链接 位置 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>
Counties Show 视图是这样的:
<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** 中。就关系/数据而言,数据库表肯定设置得很好。任何想法都受到广泛欢迎...
位置控制器:
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 感谢我添加了位置控制器
-
这很好,但您是否注意到我关于重叠路线的其他评论?这个非常重要。 Rails 无法区分指定的 2 条路线。我会将它们更改为
get "/counties/:county_name_with_prefix" => "counties#show_by_name"和get "/locations/:location_name_with_prefix" => "locations#show_by_name",这样它们就不会重叠并且可以按预期工作。 -
@engineersmnky 是的,你完全正确。这也让我对路由有了更多的了解,非常感谢。
标签: ruby-on-rails ruby controller routes