Ruby on rails 3 解析URL并删除结束部分

Ruby on rails 3 解析URL并删除结束部分,ruby-on-rails-3,Ruby On Rails 3,我正在尝试解析URL。例如,我正在尝试退出: ~/locations/1 => [locations,1] ~/locations/1/comments => [locations,1] ~/locations/1/comments/22 => [locations,1] ~/locations/1/buildings/3 => [buildings,3] ~/locations/1/buildings/3/comments => [buildings,3] ~/l

我正在尝试解析URL。例如,我正在尝试退出:

~/locations/1 => [locations,1]
~/locations/1/comments => [locations,1]
~/locations/1/comments/22 => [locations,1]
~/locations/1/buildings/3 => [buildings,3]
~/locations/1/buildings/3/comments => [buildings,3]
~/locations/1/buildings/3/comments/34 => [buildings,3]
格式相当一致。我从阵列开始,但似乎仍然失败:

@request_path = request.path.downcase.split('/')
@comment_index = @request_path.index("comments").to_i
if @comment_index > 0
  @request_path = @request_path.drop_while { |i| i.to_i >= @comment_index }
end
resource, id = @request_path.last(2)

我添加了小写,以防有人手动键入大写URL。drop\u while似乎不起作用。

处理代码后,您有什么样的输出

编辑 您的问题是将元素
转换为_i
,它是
0
。但您想要比较元素的
索引
,但通常可以使用该方法获得该情况下元素的
索引

正确的方法:

@request_path.drop_while { |i| @request_path.index(i) >= @comment_index }
def resource_details(path)
    resource_array = path.downcase.split("/").reject!(&:empty?)
    key = resource_array.index("comments")
    return key.present? ? (resource_array - resource_array[key..key + 1]).last(2) : resource_array.last(2)
 end
您可以分析
路径
,而无需
时删除

我的解决方案:

@request_path.drop_while { |i| @request_path.index(i) >= @comment_index }
def resource_details(path)
    resource_array = path.downcase.split("/").reject!(&:empty?)
    key = resource_array.index("comments")
    return key.present? ? (resource_array - resource_array[key..key + 1]).last(2) : resource_array.last(2)
 end
它将为您的路径剪切
[“comments”]
[“comments”,“2”]

调用该方法:

1.9.3p0 :051 > resource_details("/locations/1/buildings/3/comments")
 => ["buildings", "3"] 

1.9.3p0 :052 > resource_details("/locations/1/comments/2")
 => ["locations", "1"] 

我的代码运行正常,只是它似乎没有删除注释。我想要的是不是注释的下划线资源。注释是多态的,我试图解析给定路径的资源和id,而不管是否存在注释。