我想根据数据库表中的type
列为我的网址添加后缀。
# shop_controller.rb
...
def near
@shop = Shop.find(params[:id])
@type = @shop.type
end
# routes.rb
resources :spots do
member do
get :near
end
end
我的网页目前位于app/views/shops/nearby.html.erb
。目前生成的网址是:
http://localhost/shops/1/near
我没有为不同的类型创建多个页面:nearby_country.html.erb
,nearby_state.html.erb
,nearby_city.html.erb
这不是RESTful,我宁愿在此网址上附加类型来按类型过滤商店,以便将来当我有更多类型时,它会自动显示:
http://localhost/shops/1/near_country
http://localhost/shops/1/near_state
http://localhost/shops/1/near_city
我也希望能够为我的菜单执行自定义路径,如:
nearby_country_shop_path
nearby_state_shop_path
nearby_city_shop_path
有人可以提供一些提示吗?谢谢!
答案 0 :(得分:1)
见3.1节:
http://guides.rubyonrails.org/routing.html
但你可能不得不使用以下路线:
http://localhost/shops/1/near?country
http://localhost/shops/1/near?state
http://localhost/shops/1/near?city
另见:
http://railscasts.com/episodes/203-routing-in-rails-3
http://railscasts.com/episodes/231-routing-walkthrough
http://railscasts.com/episodes/232-routing-walkthrough-part-2
答案 1 :(得分:1)
这不是您要求的,但您可以在路线中添加参数x
,例如。
resources :spots do
member do
get 'near/:x', :action => :near, :as => :near
end
end
这应该为您提供以下网址:
/spots/1/near/country
/spots/1/near/state
/spots/1/near/city
..和路线如:
near_spot GET /spots/:id/near/:x(.:format) {:action=>"near", :controller=>"spots"}
..和url助手如:
near_spot_path(spot_id, :country)
near_spot_path(spot_id, :state)
等