在Rakefile中访问命名路由

Dex*_*Dex 9 rake ruby-on-rails rails-routing

我有一些像这样的命名路线rake routes:

birthdays GET    /birthdays(.:format)                             birthdays#index
Run Code Online (Sandbox Code Playgroud)

在rakefile中,我只是希望能够birthdays_url在我的视图中调用.

task :import_birthdays => :environment do
  url = birthdays_url
end
Run Code Online (Sandbox Code Playgroud)

但是我收到了一个错误 undefined local variable or method 'birthdays_url' for main:Object

Jam*_*ier 21

您可以在rake任务中使用此示例代码:

include Rails.application.routes.url_helpers
puts birthdays_url(:host => 'example.com')
Run Code Online (Sandbox Code Playgroud)

或者您可以在rake任务中使用此示例代码:

puts Rails.application.routes.url_helpers.birthdays_url(:host => 'example.com')
Run Code Online (Sandbox Code Playgroud)

如果您只想要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
Run Code Online (Sandbox Code Playgroud)