Ruby on rails Rails-to_参数将斜杠更改为";%2F";,可以覆盖这个吗?

Ruby on rails Rails-to_参数将斜杠更改为";%2F";,可以覆盖这个吗?,ruby-on-rails,ruby,routes,ruby-on-rails-5,ancestry,Ruby On Rails,Ruby,Routes,Ruby On Rails 5,Ancestry,我正在使用gem祖先,并试图构建我的路线来显示父母和孩子之间的等级关系 位置.rb def to_param if self.ancestors? get_location_slug(parent_id) + "/" + "#{slug}" else "#{slug}" end end def get_location_slug(location_id) location = Location.find(location_id) "#{location.sl

我正在使用gem祖先,并试图构建我的路线来显示父母和孩子之间的等级关系

位置.rb

def to_param
  if self.ancestors?
    get_location_slug(parent_id) + "/" + "#{slug}"
  else
    "#{slug}"
  end
end

def get_location_slug(location_id)
  location = Location.find(location_id)
  "#{location.slug}"
end
这项工作99%完美,并清晰地显示了我的路线-但它在我与家长的路线中显示的是“%2F”而不是“/”:

localhost:3000/locations/location-1 (perfect)
localhost:3000/locations/location-1%2Flocation-2 (not quite perfect)
def get_full_location_path(location)
  if location.ancestors?
    location_child_path(location.root, location)
  else
    location_path(location)
  end
end
Routes.rb(共享以防万一)


附加问题:这目前包括根位置和子位置。我如何将其扩展到孙辈和曾孙辈所在地?提前谢谢

只是想分享我的解决方案,希望能帮助到别人

首先,我清理了模型中的方法:

def to_param
  slug
end
然后,调整了我的路线:

get 'locations/:id', to: 'locations#show', as: :location
get 'locations/:parent_id/:id', to: 'locations#show_child', as: :location_child
然后,我在我的应用程序助手中创建了一个新方法,为有/没有父对象的位置生成这些URL:

localhost:3000/locations/location-1 (perfect)
localhost:3000/locations/location-1%2Flocation-2 (not quite perfect)
def get_full_location_path(location)
  if location.ancestors?
    location_child_path(location.root, location)
  else
    location_path(location)
  end
end
最后,在我的视图中,我只需调用我的helper方法来生成正确的URL:

<%= link_to location.name, get_full_location_path(location) %>


这似乎很有效,但我的下一个任务是将其扩展到包括祖父母和曾祖父母。任何建议都将不胜感激

match'locations/:id/:id'
我很惊讶解析器竟然接受了这一点。我认为你的路线设置得不对。@JoshBrody我认为你是对的,看起来很奇怪。我假设我应该将第一个:id替换为:parent_id,但我不确定如果还有另一个级别该怎么办。例如,您是否知道:祖父母id是否有效?您的路线应该是您需要再经过一次。您将了解嵌套路由是如何创建的。您是否尝试将路由声明为
/…/*slug
?Rails尝试积极地参数化所有内容,以便无论您在标识符中输入什么,它都能在URL中正常工作,
/
是保留字符。