【问题标题】:In Rails 6, how can I use a route parameter as the controller method name?在 Rails 6 中,如何使用路由参数作为控制器方法名称?
【发布时间】:2020-07-04 21:54:12
【问题描述】:

我有一个包含多个操作的报告控制器,每个操作用于每种报告。

我打算让他们这样走:

/reports/:report_type

我希望将 report_type 字符串片段用作控制器名称,这样我就可以有一条路由来处理所有这些,如下所示:

  get 'reports/:rpt_type' => "reports#:rpt_type"

...例如可以解决这个问题:

  get 'reports/song_performers' => 'reports#song_performers'

这可能吗?如果可以,怎么做?

【问题讨论】:

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


    【解决方案1】:

    是的,是的。你可以在控制器中处理这个,而不是在 routes.rb 文件中:

    # reports_controller.rb
    def show
      send(params[:rpt_type])
    end
    
    private
    def song_performers
      # do stuff
    end
    
    def other_type
      # do other stuff
    end
    
    # in routes.rb
    get 'reports/:rpt_type', to: 'reports#show'
    

    【讨论】:

    • 这行得通,但我需要将params(:rpt_type) 更改为params[:rpt_type]get 'reports/:rpt_type' to: 'reports#show' 更改为get 'reports/:rpt_type', to: 'reports#show'。我什至能够删除单独的实例方法并将所有逻辑放在show 方法中。谢谢!
    • 我不确定我是否可以编辑答案代码,但看起来其他人做了第一次更正,所以我想我会做第二次。
    猜你喜欢
    • 1970-01-01
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多