微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby-on-rails – 如何在routes.rb中创建自定义路由助手

我的路线中有几个重现的模式,我想通过创建一个为我创建这些路径的方法来使其成为干.

我想要完成的一个例子可以在Devise gem中看到,您可以使用以下语法:

#routes.rb
devise_for :users

这将产生Devise所需的所有路线.我想创造类似的东西.例如说我有以下路线:

resources :posts do
  member do
    get 'new_file'
    post 'add_file'
  end
  match 'files/:id' => 'posts#destroy_file',:via => :delete,:as => :destroy_file
end

resources :articles do
  member do
    get 'new_file'
    post 'add_file'
  end
  match 'files/:id' => 'articles#destroy_file',:as => :destroy_file
end

这开始变得凌乱很快,所以我想找到一种方式来做到这一点:

resources_with_files :posts
resources_with_files :articles

所以我的问题是,如何创建resources_with_files方法

解决方法

把它放在像lib / routes_helper.rb这样的东西:
class Actiondispatch::Routing::Mapper
  def resources_with_files(*resources)
    resources.each do |r|
      Rails.application.routes.draw do
        resources r do
          member do
            get 'new_file'
            post 'add_file'
            delete 'files' => :destroy_file
          end
        end
      end
    end
  end
end

并在config / routes.rb中要求它

原文地址:https://www.jb51.cc/ruby/272722.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐