【问题标题】:Advanced Routing with Rails3Rails3 高级路由
【发布时间】:2010-09-06 16:05:52
【问题描述】:

我想在我的路由中使用正则表达式。我有一个 Products 控制器,但我想要一个不同的 URL 结构来访问产品

这些 URL 应该在我的控制器中调用一个操作 (Products:show_category(:category))

这样的事情可能吗?

match "(this|that|andthat)" => "products#show_category", :category => $1

动作应该是这样的

def show_category
  puts params[:category] # <-- "this" if http://host/this/ is called
  # ...
end

【问题讨论】:

    标签: ruby-on-rails regex routing


    【解决方案1】:

    我还没有实际测试过,但试试吧:

    match ':category' => 'products#show_category', :constraints => { :category => /this|that|andthat/ }
    

    【讨论】:

    • 太好了,完美!感谢 :constraints-Option 的提示
    【解决方案2】:

    我不太确定这是否能回答您的问题,但您可以在 routes.rb 中添加一个集合:

    resources :products do
      collection do
        get :category1
        get :category2
        get :category3
      end
    end
    

    如果您随后运行rake routes,您会看到您有像/products/category1products/category2 这样的网址。可以像往常一样在控制器中定义类别 1、2 和 3:

    def category1
      #custom code here
    end
    
    def category2
      #custom code here
    end    
    
    def category3
      #custom code here
    end
    

    正如我所说,我不太确定这是否是您想要做的,但希望对您有所帮助!

    【讨论】:

    • 我认为有更聪明的方法可以做到这一点。我想将所有三个 url 都指向同一个动作,并将类别名称作为参数。我稍微协调一下这个问题。
    • 当然,那么上面的建议就完美了!
    猜你喜欢
    • 1970-01-01
    • 2010-12-23
    • 2014-10-28
    • 2011-09-02
    • 2018-06-26
    • 1970-01-01
    • 2011-10-12
    • 2023-03-08
    • 1970-01-01
    相关资源
    最近更新 更多