【问题标题】:Rails 4 - Hash in route gets rendered wronglyRails 4 - 路径中的哈希被错误地呈现
【发布时间】:2014-08-29 20:37:23
【问题描述】:

我在 routes.rb 中有这行代码

get 'products#:id' => 'products#index', as: :products_hash

它可以工作,但问题是井号 (#) 被呈现为 %23。

http://localhost:3000/products%2368

应该是这样的:

http://localhost:3000/products#68

我怎样才能做到这一点?谢谢!

【问题讨论】:

  • 是的,但是真的没用哈哈
  • 我得问问。为什么要使用http://localhost:3000/products#68 而不是http://localhost:3000/products/68
  • 我相信您应该在link_to 助手的anchor 键中手动指定它。在路由中指定它可能是不可能的,因为路由主要用于解析和选择路径 - 而 # 之后的部分不是路径的一部分。不可能我的意思是你需要修改rails的方法才能使它工作。也许写一个助手。
  • 你不想要这个 - 浏览器根本不会将 # 后面的内容发送到服务器

标签: ruby-on-rails ruby ruby-on-rails-4 routes


【解决方案1】:

导轨

我觉得你错过了Rails' routing system 的要点,即你应该围绕对象构建它(因此你为什么调用resources :controller 等)。

虽然我不明白你为什么要定义你的路线,但我会给你一些想法。在 Rails 中有一个 "wildcard" 设置用于您的路由,它允许您在典型的基于“CRUD”的应用程序范围之外定义和传递参数给您的应用程序:

#config/routes.rb
get 'products#*id' => 'products#index', as: :products_hash

这将使您能够向以下路由发送请求:

<%= link_to "Product", products_hash_path("68") %>

然后您就可以调用控制器中的参数:

#app/controllers/products_controller.rb
class ProductsController < ApplicationController
   def index
      id = params[:id]
   end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 2011-03-29
    • 2023-03-29
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多