将URL分成几部分

时间:2014-07-04 19:27:59

标签: ruby-on-rails ruby

我想将网址分成几部分,具体取决于网址是否以尾部斜杠结尾。

以下是一些例子:

1. www.example.com/
2. www.example.com/category1/
3. www.example.com/category1/subcat1/

1. category_path = /
file_name = nil

2. category_path = /category1  
file_name = nil

3. category_path = /category1/subcat1/
file_name = nil

示例集#2

1. www.example.com/page1
2. www.example.com/category1/page2
3. www.example.com/category1/subcat1/page3

1. category_path = nil
file_name = page1

3. category_path = /category1/
file_name = page2


3. category_path = /category1/subcat1/
file_name = page3

我应该如何将此URL字符串拆分为category_path和file_name路径?

注意:如果网址以尾部斜杠结尾' /'那么URL只有一个category_path,而file_name将是nil。如果没有尾部斜杠,则最后一部分是file_name。

在Rails中,request.url似乎没有获取尾随斜杠。 如果我在控制器中输出request.url的值,它甚至不会确认有斜杠

e.g。

def test
   has_file = request.url.end_with?("/")
  render text: "url = #{request.url}, has_file = #{has_file}"
end

现在,如果我添加或远程拖尾斜线,它似乎甚至没有注册。尾部斜杠是否会忽略标题级别或其他内容?

1 个答案:

答案 0 :(得分:0)

<强>路由

我认为你没有任何理由不使用nested routing

#config/routes.rb
resources :categories do
   resources :subcategories #-> domain.com/categories/1/subcategories/4
end

这是传统的方式对此进行排序 - 允许您将上面的变量作为params传递给控制器​​

-

如果你想重构它以摆脱资源标识(categories / subcategories)等,你会想要使用path: ""技巧:

#config/routes.rb
resources :categories, path: "" do
   resources :subcategories, path: "" #-> domain.com/1/4
end 

这将转化为以下内容:

#app/controllers/subcategories_controller.rb
Class SubcategoriesController < ApplicationController
   def index
      params[:category_id] #-> 1
      params[:id] #-> 4
   end
end
相关问题