【问题标题】:Rails - to_param changes slash to "%2F", possible to override this?Rails - to_param 将斜杠更改为“%2F”,可以覆盖它吗?
【发布时间】:2018-07-09 03:16:07
【问题描述】:

我正在使用 gem Ancestry,并尝试构建我的路线以显示父母和孩子之间的层次结构。

Location.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)

Routes.rb(共享以防万一)

match 'locations/:id' => 'locations#show', :as => :location, :via => :get
match 'locations/:parent_id/:id' => 'locations#show', as: :location_child, via: :get

额外问题:这目前涵盖 root 位置和 child 位置。我如何将其扩展到 孙子 位置和 曾孙 位置?提前致谢!

【问题讨论】:

  • match 'locations/:id/:id' 我很惊讶它甚至被解析器接受了。我认为您的路线设置不正确。
  • @JoshBrody 我认为你是对的,它看起来很奇怪。我假设我应该用 :parent_id 替换第一个 :id,但我不确定如果有另一个级别该怎么办。例如,您知道 :grandparent_id 是否有效吗?
  • 你的路线应该是RESTful
  • 您需要再通过guides.rubyonrails.org/routing.html 一次。您将弄清楚嵌套路由是如何创建的。
  • 您是否尝试过将您的路线声明为/.../*slug? Rails 尝试积极地参数化所有内容,以便无论您在标识符中输入什么内容,它都能在 URL 中正常工作,而 / 是保留字符。

标签: ruby-on-rails ruby routes ruby-on-rails-5 ancestry


【解决方案1】:

只是想分享我的解决方案,希望对某人有所帮助。

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

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:

def get_full_location_path(location)
  if location.ancestors?
    location_child_path(location.root, location)
  else
    location_path(location)
  end
end

最后,在我看来,我只是调用我的辅助方法来生成正确的 URL:

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

这似乎运作良好,但我的下一个任务是将其扩展到祖父母和曾祖父母。任何建议表示赞赏!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-07
    • 2016-04-19
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多