I have some named routes like this rake routes
:
birthdays GET /birthdays(.:format) birthdays#index
In a rakefile I simply want to be able to call birthdays_url
like I would in my view.
task :import_birthdays => :environment do
url = birthdays_url
end
But I'm getting an error undefined local variable or method 'birthdays_url' for main:Object
TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.
Rails routing is a two-way piece of machinery – rather as if you could turn trees into paper, and then turn paper back into trees. Specifically, it both connects incoming HTTP requests to the code in your application's controllers, and helps you generate URLs without having to hard-code them as strings.
You can either use this example code in your rake task:
include Rails.application.routes.url_helpers
puts birthdays_url(:host => 'example.com')
or you can use this example code in your rake task:
puts Rails.application.routes.url_helpers.birthdays_url(:host => 'example.com')
If you only want the path part of the URL, you can use (:only_path => true)
instead of (:host => 'example.com')
. So, that would give you just /birthdays
instead of http://example.com/birthdays
.
You need either the (:host => 'example.com')
or (:only_path => true)
piece, because the rake task doesn't know that bit of information and will give this error without it:
Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true
for Rails 4 include code with your domain at the top of your rake task
include Rails.application.routes.url_helpers
default_url_options[:host] = 'example.com'
use this:
Rails.application.routes.url_helpers.birthdays_url
or to be less verbose:
include Rails.application.routes.url_helpers
url = birthdays_url
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With