我有一些命名的路由,像这样的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
发布于 2013-07-23 08:55:29
您可以在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的路径部分,则可以不使用(:host => 'example.com'),而使用(:only_path => true)。所以,这将只给你/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发布于 2015-07-11 01:49:18
对于Rails4,在rake任务的顶部包含域的代码
include Rails.application.routes.url_helpers
default_url_options[:host] = 'example.com'发布于 2013-07-23 08:48:46
使用以下命令:
Rails.application.routes.url_helpers.birthdays_url或者说得简单一点:
include Rails.application.routes.url_helpers
url = birthdays_urlhttps://stackoverflow.com/questions/17799735
复制相似问题