Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

link_to vs url_for vs path in Rails

I'm starting learn Ruby on Rails and I have some doubts.

I already see the Rails documentation but I don't understand at all the differences between:

  • url_for
  • link_to
  • path

And how I can use / discover the paths of my application? Further, can I send a parameter in path, like:

<%= users_path + "/user.id/" %>  

Is there anything like that?

like image 984
Paladini Avatar asked Sep 28 '13 04:09

Paladini


1 Answers

url_for provides you the full url to the website, for example: www.example.com/my/path would come from something like url_for my_path_url.

link_to gives you a link to a specific path, for example:

link_to example_path,"click me"

would result in

<a href="www.example.com/my/path">click me</a>

You can also use this with url_for like this:

link_to url_for(my_resource_path)

resource_path is used to reference a path in your routes.rb file. For example, if you have

match '/my/:id/page' => 'my#page'

you could use my_page_path(...).

If you need the :id for the path, you could pass it as in the parameters to your resource_path like this: my_page_path(current_user.id).

In addition, you can add in other query parameters by simply appending them to the preset route parameters:

my_page_path(current_user.id,:hello => "world")

You ask about whether you can add paths to an existing path. Yes, you can, as these functions simply return strings to the caller, so for all intents and purposes you could do exactly what you wrote as long as that path conjugates with your string into a proper route.

like image 72
IT Ninja Avatar answered Sep 23 '22 06:09

IT Ninja