我有一些像这样的命名路由 rake routes
:
birthdays GET /birthdays(.:format) birthdays#index
在 rakefile 中,我只想能够调用
birthdays_url
就像我认为的那样。task :import_birthdays => :environment do
url = birthdays_url
end
但我收到错误
undefined local variable or method 'birthdays_url' for main:Object
最佳答案
您可以在您的 rake 任务中使用此示例代码:
include Rails.application.routes.url_helpers
puts birthdays_url(:host => 'example.com')
或者您可以在您的 rake 任务中使用此示例代码:
puts Rails.application.routes.url_helpers.birthdays_url(:host => 'example.com')
如果你只想要 URL 的路径部分,你可以使用
(:only_path => true)
而不是 (:host => 'example.com')
.所以,那只会给你 /birthdays
而不是 http://example.com/birthdays
.您需要
(:host => 'example.com')
或 (:only_path => true)
一块,因为 rake 任务不知道那一点信息,没有它就会出现这个错误:Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true
关于ruby-on-rails - 访问 Rakefile 中的命名路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17799735/