3

Inside a controller I've tried to run this code for when users that are already logged in stumble across the sign up page

def index
  if current_user
    redirect_to homebase_url #should provide url to home for logged in users
  end
end

I've done what the rails error message said and have added: include Rails.application.routes.url_helpers to the containing controller class. Still getting this error though. Definitely do not want to hardcode URLs into there for legacy purposes. Thanks

boulder_ruby
  • 38,457
  • 9
  • 79
  • 100
  • 1
    Typically, you shouldn't need need to include url_helpers in a Rails controller. Two questions: (1) Are you sure the error is being thrown by the line calling `redirect_to homebase_url`? If it's being thrown somewhere else (such as within a template), you may have to include the url_helpers somewhere else, like the ApplicationHelper. (2) Would you be able to show a full stack trace along with more of the full controller class? – Charlie Tran Jan 30 '17 at 01:46
  • I had added the `include Rails.application.routes.url_helpers` to an initializer and somehow that was screwing everything up. Figured it out right after I left the bounty. I guess if anything I wouldn't mind knowing why that caused that.. – boulder_ruby Jan 30 '17 at 02:45
  • Could you post the entire controller class and the initializer, there might be an issue with including the UrlHelpers in the initializer before routes are loaded. – Jan Bussieck Jan 30 '17 at 14:29
  • You haven't provided enough code for us to help. – coreyward Feb 01 '17 at 00:13
  • Please post the full error with backtrace - it isn't coming from that line unless that line is surrounded by unusual code. – sevenseacat Feb 02 '17 at 11:43

2 Answers2

3

Remove the include Rails.application.routes.url_helpers declaration, it's not needed unless it's in something like a helper. Routes are included in controllers by default. Including it in a model or controller/initializer (routes are loaded before initializers) is against MVC architecture and might cause unwanted behaviour.

Shannon
  • 2,988
  • 10
  • 21
1

I recommend using homebase_path instead of homebase_url

For example when looking at http://stackoverflow.com/questions/41903124/getting-runtimeerror-in-order-to-use-url-for-you-must-include-routing-helper/42048113#42048113

console.log(window.location.pathname) // => "/questions/41903124/getting-r..."
console.log(window.location.host) // => "stackoverflow.com"

path is the stuff after the domain name(host).

a complete URL(in your case homebase_url) requires both a host and a path. In development its a bit awkward to get a host because its a different value in production than it is in development.

Blair Anderson
  • 19,463
  • 8
  • 77
  • 114