【发布时间】:2021-10-04 07:30:38
【问题描述】:
你好 Rails Stack 社区!
我想为模型生成一个公共共享 URL,该 URL 应始终包含一些哈希以防止 URL 猜测。
这是我想出的:
# routes.rb
resources :reports do
member do
get '/public/:public_hash', to: 'reports#public', as: 'public'
end
end
# In some view
public_report_path(@report, @report.public_hash)
# /reports/1234/public/xxxx-xxxxx-xxxxx-xxxx
这工作好的,但我觉得应该有一个更优雅的方式来做到这一点从路线定义。我想做的是public_report_path(@report),它应该在生成URL时自动包含public_hash。
以下内容:
# routes.rb
resources :reports do
member do
get :public, do |route_object|
route_object.path.push(route_object.params.first.public_hash)
end
end
end
# In some view
public_report_path(@report)
# /reports/1234/public/xxxx-xxxxx-xxxxx-xxxx
我看到了一些解决方案,其中url_for 的定义被覆盖了我宁愿不覆盖核心功能。然后我更喜欢给 url helper 提供 2 个参数。
【问题讨论】:
-
我认为路径助手是用来从中选择 id 的,除非你用
#to_param做某事。我不是 100% 的人
标签: ruby-on-rails routes ruby-on-rails-6