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 + "/" %> 

Is there anything like that?

1

1 Answer

url_for provides you the full url to the website, for example: 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="">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.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like