Siddharth
Siddharth

Reputation: 893

To print root url in rails 3 application using helper

OK I have a pretty simple problem which I'm not being able to solve. I have a link that I'm showing to my users by the following ruby code in a rails 3 application:-

<%= link_to linkbunch_url(@link.link), linkbunch_url(@link.link) %>

This is printing a url like this:-

http://localhost:3000/linkbunches/7yae8t

Now I don't want this "linkbunches" to be part of my url. So I changed my routes.rb file and defined a path like:-

match "/:id" => "linkbunches#show"

So when I'm changing the url from http://localhost:3000/linkbunches/7yae8t to http://localhost:3000/7yae8t it's taking me to the same page. No problem at all. But I don't understand how to actually change the ruby code so that it don't prints the controller name. I tried with root_url(@link.link) but it didn't work...

Upvotes: 1

Views: 583

Answers (2)

Jiř&#237; Posp&#237;šil
Jiř&#237; Posp&#237;šil

Reputation: 14412

@Deefour is right. One thing I would recommend however is to always limit your HTTP methods as you see fit. So instead of match, use get:

get "/:id" => "linkbunches#show", as: :linkbunch

You could use match with via: :get (this will be required when using match in the future Rails versions) but prefer the other explicit form.

Upvotes: 0

deefour
deefour

Reputation: 35370

You can explicitly name the route with the :as option.

match "/:id" => "linkbunches#show", as: :linkbunch

Notice how your original route is nameless

➜  ~ ✗ rake routes | grep bunch
                /:id(.:format)    linkbunches#show

and once you've named it as I showed above

➜  ~ ✗ rake routes | grep bunch
   linkbunch    /:id(.:format)    linkbunches#show

This will allow you to continue using linkbunch_url(@link.link) in your views.

Upvotes: 3

Related Questions