Created
November 12, 2011 23:34
-
-
Save house9/1361290 to your computer and use it in GitHub Desktop.
Sample Routes and Links with Rails 3 in the console
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# create new rails app | |
rails new routes_and_stuff | |
cd routes_and_stuff | |
# generate a user scaffold | |
rails generate scaffold user | |
bundle exec rake db:migrate | |
# checkout routes | |
bundle exec rake routes | |
# test some in the console | |
rails console | |
puts new_user_path | |
# => NameError: undefined local variable or method `new_user_path' for main:Object | |
# we need to include the routes module | |
include Rails.application.routes.url_helpers | |
puts new_user_path | |
# => /users/new | |
# => nil | |
# much better, now lets try testing a link_to | |
link_to 'New User', new_user_path | |
# => NoMethodError: undefined method `link_to' for main:Object | |
# need the module that contains link_to | |
include ActionView::Helpers | |
link_to 'New User', new_user_path | |
# => SystemStackError: stack level too deep from ... Maybe IRB bug!! | |
# ok, a road I do not want to go down, lets do this the easy way | |
# you might need to exit and re-launch console, then... | |
class LinkHelper; include ActionView::Helpers; end | |
helper = LinkHelper.new | |
helper.link_to 'New User', new_user_path | |
# => "<a href=\"/users/new\">New User</a>" | |
helper.link_to 'Users', users_path | |
# => "<a href=\"/users\">Users</a>" | |
# now we can test out some stuff, like request the same page with .csv extension | |
params = { :email => "%@testing.com", :is_active => true } | |
helper.link_to 'Users CSV Export', users_path(params.merge(:format => :csv)) | |
# => "<a href=\"/users.csv?email=%25%40testing.com&is_active=true\">Users CSV Export</a>" | |
# http://house9.blogspot.com/2011/11/sample-routes-and-links-with-rails-3-in.html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment