【问题标题】:Colons as divider with Rails Route?冒号作为 Rails Route 的分隔符?
【发布时间】:2013-03-10 16:36:21
【问题描述】:

我想在 Rails 路由 url 中使用冒号作为分隔符,而不是正斜杠。有可能做到这一点吗?


我正在追求类似以下的东西

match '*page_path/:title ":" *section_path ":" :section_title' => 'pages#show'

所以对于 url food/fruit/apples:cooking:pie:apple_pie 将返回参数:

:page_path = "food/fruit"
:title = "apples"
:section_path = "cooking:pie"
:section_title = "apple_pie"

这在 Rails 中可行吗?

【问题讨论】:

  • 正斜杠有什么问题?

标签: ruby-on-rails regex url routes colon


【解决方案1】:

这是一种方法:

match 'food/fruit/:id' => 'pages#show' # add constraints on id if you need

class Recipe < ActiveRecord::Base
  def self.from_param( param )
    title, section_path, section_title = extract_from_param( param ) 
    # your find logic here, ex: find_by_title_and_section_path_and_section_title...
  end

  def to_param
    # build your param string here, 
    # ex: "#{title}:#{section_path}:#{section_title}" 
    # Beware ! now all your urls relative to this resource
    # will use this method instead of #id. 
    # The generated param should be unique, of course.
  end

  private

  def self.extract_from_param( param )
    # extract tokens from params here
  end
end

然后在你的控制器中:

 @recipe = Recipe.from_param( params[:id] )

请注意,使用内置to_param 方法是可选的。

【讨论】:

    猜你喜欢
    • 2010-12-12
    • 2019-02-22
    • 2011-03-26
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    相关资源
    最近更新 更多