ruby-on-rails - Rails 4.1.2 - to_param 转义斜杠(并破坏应用程序)

标签 ruby-on-rails ruby ruby-on-rails-4.1 actionpack

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

class Machine < ActiveRecord::Base
  def to_param
    MachinePrettyPath.show_path(self, cut_model_text: true)
  end
end

问题是,自从 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

我试过了 by recommendation in the thread仅对 show 方法使用 glob 参数以确保其有效:

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

scope format: false do
 get '/machines/*id', to: "machines#show"
end

但是绝对不行。我仍然有这样的损坏链接:

http://localhost:3000/machines/tractor%2Fminitractor%2Fmodel1%2F405

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

http://localhost:3000/machines/tractor/minitractor/model1/405

然后尝试访问路径,然后页面就会打开。

有什么办法可以解决这个问题吗?

最佳答案

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

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

pretty_machine_path(machine.subcategory, machine.brand, machine.model, machine.id)

这太丑陋了,显然你不想一遍又一遍地做。您可以向 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

关于ruby-on-rails - Rails 4.1.2 - to_param 转义斜杠(并破坏应用程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25031791/

相关文章:

ruby-on-rails - Rails 4 - Gem::LoadError:为数据库适配器指定了 'mysql2',但未加载 gem

ruby-on-rails - link_to_unless问题

ruby-on-rails - 在 session_controller#create 上设计错误数量的参数(2 为 1)

ruby-on-rails - 如何在 mod_ajp Apache 2 代理后面的 jRuby 上运行 Rails 3.0

ruby - 比较二维数组

ruby-on-rails - PDFKit wkhtmltopdf :root_url Unknown long argument --root-url

arrays - 如何在 ruby​​ 中返回相交数组并保留大写/小写?

ruby-on-rails - 在 Rails 4.1 中,如何通过枚举符号查找记录?

ruby-on-rails - 在局部文件中本地定义的变量对于调用的 erb 模板是否也可见?

java - 实例变量会持续多长时间?在 Rails 中?在 java ?在 PHP 中?