Rails 4.1.2 - to_param转义斜杠(并打破应用程序)

Exi*_*iRe 6 ruby ruby-on-rails actionpack ruby-on-rails-4.1

我在我的应用程序中to_param使用创建自定义URL(此自定义路径包含斜杠):

class Machine < ActiveRecord::Base
  def to_param
    MachinePrettyPath.show_path(self, cut_model_text: true)
  end
end
Run Code Online (Sandbox Code Playgroud)

问题是,由于Rails 4.1.2行为已更改且Rails不允许在URL中使用斜杠(使用自定义URL时),因此它会转义斜杠.

我有这样的路线:

Rails.application.routes.draw do
  scope "(:locale)", locale: /#{I18n.available_locales.join("|")}/ do
      resources :machines, except: :destroy do
          collection do
            get  :search
            get  'search/:ad_type(/:machine_type(/:machine_subtype(/:brand)))', action: 'search', as: :pretty_search

            get  ':subcategory/:brand(/:model)/:id', action: 'show', as: :pretty
            patch ':subcategory/:brand(/:model)/:id', action: 'update'                                  # To be able to update machines with new rich paths.
          end
      end
  end
end
Run Code Online (Sandbox Code Playgroud)

我尝试在线程中推荐使用glob param只为show方法确保它的工作原理:

resources :machines, except: :destroy do
 #...
end

scope format: false do
 get '/machines/*id', to: "machines#show"
end
Run Code Online (Sandbox Code Playgroud)

但它绝对不起作用.我仍然有这样断开的链接:

http://localhost:3000/machines/tractor%2Fminitractor%2Fmodel1%2F405
Run Code Online (Sandbox Code Playgroud)

当然,如果我替换自己的转义斜杠:

http://localhost:3000/machines/tractor/minitractor/model1/405
Run Code Online (Sandbox Code Playgroud)

并尝试访问路径,然后打开页面.

任何想法如何解决这个问题?

And*_*rew 1

我在使用自动生成的 url 帮助程序时遇到了同样的问题。我使用调试器跟踪新行为的源头(ActionDispatch::Journey::Visitors::Formatter 周围的某个位置),但没有找到任何有希望的解决方案。看起来参数化模型现在被严格视为路径的单个斜杠分隔段并相应地转义,没有其他选项告诉格式化程序。

据我所知,让 url 帮助器生成旧结果的唯一方法是使用原始路由文件并分别传递每个段,如下所示:

pretty_machine_path(machine.subcategory, machine.brand, machine.model, machine.id)
Run Code Online (Sandbox Code Playgroud)

这实在是太丑陋了,而且显然不是你想要一遍又一遍地做的事情。您可以向 MachinePrettyPath 添加一个方法,以将段生成为数组,并为帮助程序分解结果(例如pretty_machine_path(*MachinePrettyPath.show_path_segments(machine))),但这仍然相当冗长。

在上述令人头痛的问题和您链接到的 Rails 票证中开发人员的“您做错了”态度之间,对我来说最简单的选择是硬着头皮编写自定义 URL 帮助程序,而不是使用 to_param。我还没有找到一个“正确”方法的好例子,但是像这个简单的例子应该可以达到目的:

#app/helpers/urls_helper.rb
module UrlsHelper
  def machine_path(machine, options = {})
    pretty_machine_path(*MachinePrettyPath.show_path_segments(machine), options)
  end
end

#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  helper :urls #for the views
  include UrlsHelper #for controllers
  #...
end
Run Code Online (Sandbox Code Playgroud)