在生成路由的 URL 中自动使用模型属性

时间:2021-07-28 14:36:48

标签: ruby-on-rails routes ruby-on-rails-6

你好 Rails Stack 社区! <3

我想生成一个模型的公共共享 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 个参数。

1 个答案:

答案 0 :(得分:1)

为自己省去很多麻烦并在 Rails 迁移中使用 uuid?

https://guides.rubyonrails.org/v5.0/active_record_postgresql.html#uuid

您需要做的就是在迁移中运行它:

  create_table : reports, id: :uuid  do |t|
    t.timestamps
  end

然后将遵守标准的铁路路线、关系等。

相关问题