【问题标题】:Accessing Named Routes in Rakefile在 Rakefile 中访问命名路由
【发布时间】:2026-02-02 15:25:01
【问题描述】:

我有一些这样的命名路线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

【问题讨论】:

    标签: ruby-on-rails rake rails-routing


    【解决方案1】:

    您可以在 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
    

    【讨论】:

    • 我不喜欢对主机进行硬编码。所以我使用host: YOUR-APP-NAME::Application.config.action_mailer.default_url_options[:host] 这样它会从你的配置文件中获取它。
    【解决方案2】:

    对于 Rails 4,在您的 rake 任务顶部包含您的域的代码

    include Rails.application.routes.url_helpers
    default_url_options[:host] = 'example.com'
    

    【讨论】:

      【解决方案3】:

      使用这个:

      Rails.application.routes.url_helpers.birthdays_url
      

      或者不那么冗长:

      include Rails.application.routes.url_helpers
      url = birthdays_url
      

      【讨论】: