ruby-on-rails - 访问 Rakefile 中的命名路由

标签 ruby-on-rails rake rails-routing

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

相关文章:

ruby-on-rails - Bundler 找不到 gem "activerecord"的兼容版本

ruby-on-rails - rails 3 : Get current user_id to save in different model

ruby - `bundle exec rake` 还是 `rake` ? `Rake::TestTask` 怎么样?

ruby-on-rails - Rails 中的 Resource 和 Resources 有什么区别?

ruby-on-rails - [GET] "/articles/new"中的路由错误 '

ruby-on-rails - 无法将 Rails 应用程序推送到 Heroku

html - IE Intranet 兼容性 View 不包括某些字体

ruby-on-rails - 新手,关于 Rake 任务语法

ruby-on-rails - 使用 `rake test` 时出现问题

ruby-on-rails - :new, :collection and :member routes? 有什么区别