【问题标题】:How to generate a path by specifying controller and action?如何通过指定控制器和动作来生成路径?
【发布时间】:2019-04-01 09:28:43
【问题描述】:

我想从我的控制器或助手生成一个新链接。所以我不能使用视图中可用的link_to 方法。

我想通过指定控制器和操作来生成路径,而不是使用名称路径。例如:

{action: "index", controller: "accounts", id: "123"}

但是我将上述参数放入什么方法中?我还没有看到Path.new() 方法或类似的方法。

【问题讨论】:

  • 您可以在控制器中使用link_to*_pathurl_for,包括url_helpers:include Rails.application.routes.url_helpers

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


【解决方案1】:
url_for :controller => 'accounts', :action => 'index', :id => 123 

注意:5.1 之前的 Rails 版本中,url_helpers 默认不包含在控制器中。所以你必须自己包含它:

include Rails.application.routes.url_helpers

【讨论】:

  • 谢谢,我是否需要包含任何库才能使其正常工作?当我在 Rails 控制台中对其进行测试时,它会引发 NoMethodError
  • 知道了,你需要include Rails.application.routes.url_helpers
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-25
  • 2012-12-11
  • 2020-12-14
  • 1970-01-01
  • 1970-01-01
  • 2010-12-02
  • 2013-08-11
相关资源
最近更新 更多