I’d just started toying around with Ruby on Rails and had come across an issue with linking to another action in a controller from a particular view. I am almost certain it’s an issue (or lack of code) in my routes.rb file, but I think I’m misunderstanding exactly how this file works & what I have to do. I’ve got a solution but pretty sure it’s not the “best way” to do it.
I have one controller called home with two actions, index (which is the default) and newbill. Inside index.html.erb I have:
<h1>Home View</h1>
<%= link_to "new", :controller => "home", :action => "newbill" %>
However I was getting a routing error:
No route matches {:controller=>"home", :action=>"newbill"}
Doing rake routes gives me the following:
root / {:controller=>"home", :action=>"index"}
I then (following some Googling) added this code to routes.rb
match 'home/newbill' => 'home#newbill', :as => :newbill
And then in my index.html.erb I’ve got this:
<%= link_to "Name", newbill_path %>
And now this works as expected. My questions however are:
- Why does this work? What exactly is going on behind the scenes?
- Surely this is not the best way to do it? Adding another
match 'home/newbill'...for every controller / action I want to link to seems a rubbish way of doing things.
I really like Ruby, but struggling a bit with this aspect of Rails…routing in general is messing up my head a bit I think!
Any help is much appreciated 😀
Thanks,
Jack
You should check out the Rails Routing guide. A read through will help you understand what is going on behind the scenes.