对路由设置感到困惑 - Rails 3.1

时间:2011-11-16 14:45:33

标签: ruby-on-rails ruby-on-rails-3.1

我认为我因为名字而遇到冲突:

两种模式:store coupon

需要显示优惠券的网址:http://localhost/coupons/:store_name(“优惠券”写在网址中,不会替换为任何内容)

控制器名称:coupons_controller

以下是我现在的路线中的内容:

match '/coupons/:store_name' => 'coupons#index', :as => :stores

当我尝试在另一个控制器中执行redirect stores_path(store)时,我收到此错误:

No route matches {:controller=>"coupons"}

任何线索?我是铁杆新手所以我敢打赌这是一个愚蠢的错误。

更新

是否有一个中心位置告诉动态_path()函数使用特定的url结构?即无需在任何地方进行以下操作:

redirect_to stores_path(:store_name => store.store_name)

相反只使用:

redirect_to stores_path(store)

2 个答案:

答案 0 :(得分:1)

redirect_to stores_path(:store_name => store)

如果没有(现在不能确认)应该可以工作,你应该可以做(小hacky)

redirect_to stores_path+"?store_name=yourstorename"

以平静的方式做,你应该有这样的东西(在你的路线中):

resources :stores do
  resources :coupons # this will give you e.g. /stores/:store_id/coupons for the coupons#index action
end

如果您想使用商店名称而不是ID,只需搜索SO以使用“slug”或查看此处:getting a 'name' based URL in RESTful routes instead of an id based urlID + Slug name in URL in Rails (like in StackOverflow)

答案 1 :(得分:1)

是的,您可以在模型中重新定义to_param

class Store < ...
  def to_param
    store_name
  end
end