【问题标题】:Creating a named route for a controller with static actions using Rails 3 routing API使用 Rails 3 路由 API 为具有静态操作的控制器创建命名路由
【发布时间】:2011-01-04 19:20:41
【问题描述】:

我有一个基本控制器,其中包含代表静态页面的命名操作:

class YourTripController < ApplicationController
  def when_to_visit
  end

  def booking_a_trip
  end

  ...

end

我想要一个命名路由来访问这些操作,例如:

your_trip_path(:when_to_visit)

your_trip_path(:booking_a_trip)

看起来很简单吧?但我也想让 URL 使用破折号而不是下划线来生成路径:

example.com/your-trip/when-to-visit example.com/your-trip/booking-a-trip

鉴于这些限制,我的路线是什么样的?

我尝试了很多方法,这是迄今为止我最接近的方法:

  controller :your_trip, :path => 'your-trip', :as => :your_trip do
    get "when_to_visit", :path => 'when-to-visit'
    get "booking_a_trip", :path => 'booking-a-trip'
  end

这会正确地将我引导到正确的操作,但使用诸如 your_trip_path(:when_to_visit) 之类的 url 助手会导致:

没有路线匹配 {:action=>"when_to_visit", :controller=>"your_trip"}

【问题讨论】:

    标签: ruby-on-rails routing ruby-on-rails-3


    【解决方案1】:

    将 url 匹配到 controller#action 并使用 :as 指定路由名称:

    get "your-trip/when-to-visit" => "your_trip#when_to_visit", :as => "when_to_visit"
    

    网址助手也可以:

    rails c
    Loading development environment (Rails 3.0.3)
    ruby-1.8.7-p302 :001 > app.when_to_visit_path
     => "/your-trip/when-to-visit"
    

    看起来在routing-filter gem 的帮助下,有可能为带连字符的 url 编写自定义路由过滤器。对于只有几个静态页面的简单案例来说,这当然是矫枉过正。

    您的版本稍作修改即可工作:

    controller :your_trip, :path => 'your-trip', :as => :your_trip do
      get "when_to_visit", :path => 'when-to-visit', :as => :when_to_visit
      get "booking_a_trip", :path => 'booking-a-trip', :as => :booking_a_trip
    end
    

    然后将路由命名为:

    your_trip_when_to_visit
    your_trip_booking_a_trip
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-25
      • 1970-01-01
      • 2012-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      相关资源
      最近更新 更多