2

When I try to use url_for in the rails console, I see:

url_for(User.first.images.first)
NoMethodError: undefined method `url_for' for main:Object

How can I use that method in the rails console?

stevec
  • 41,291
  • 27
  • 223
  • 311

1 Answers1

8

you can use the following to check route helper methods in the console.

app.url_for(User.first.images.first)

the app would give you a view context. But beware if you are using it in the application.

raviture
  • 959
  • 7
  • 11
  • And just like that, it works! Do you know if there's any way to automatically make the rails console prepend `app.` when it's required so I can run the same code between rails console and in the application? (I find the console invaluable for quickly testing bits of code, but painful to deal with it behaving differently to the application). Just thought of this while writing this, but perhaps I should be using a debugging session for quick code tests because it will already have everything it needs.. – stevec Feb 01 '21 at 04:39
  • 1
    I would recommend using debugging session for testing your routes on views itself. checkout byebug or binding.pry options. if you still want to use the routes out of the view context you should check out https://stackoverflow.com/a/13553422/3733382. Other than this I don't think you can directly start using routes without adding something like app. or including some module ... – raviture Feb 01 '21 at 04:57
  • When testing link_to, I use app.polymorphic_url to check that the right route is specified. Here I have an "admin" namespace wrapping User. app.polymorphic_url(:admin, User.first) "http://www.example.com/admin/users/1" – Stefan Musarra Dec 02 '22 at 21:40