2

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


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

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

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

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

这在rails中可能吗?

4

1 回答 1

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方法是可选的。

于 2013-03-21T13:07:19.640 回答