I am working on the first application from the book “Head First Rails”
called “tickets”. What I do not understand is where the variable
“new_ticket_path” gets populated in the view index.html.erb
This path is made up by the rails router. If you have
‘resources :tickets’ in your routes file, then this path is generated
automatically for you. Type rake routes in your Terminal to see the
whole lot of them.
There’s an excellent Rails Guide about this, called Routing from the
Outside In.
So if I understand correctly new_ticket_path, edit_ticket_path, ticket
are like constants that RoR assigns to them specific values.
If I want to create a new link on my RoR Application to a new page
called for example “myblog”, and add it to the index page, which will be
the right syntax?
link_to “myblog”, ???
That depends on where the blog is coming from. If it is part of your
Rails application, and you are linking to it from a different part of
the same Rails application, then you might be able to do something like:
That’s assuming that your blog is rendered by the #index method of the
PostsController. Substitute your own controller name as needed.
If you have two separate Rails applications, and you want to link from
one to the other, then you can either use a hand-written link, or you
can use the :url attribute in the link_to method. Read up on the
link_to generator in the API docs:
should say: new_tickets_path. Note the plural form of tickets. At
least that is the way it is in Rails 3.09. Or maybe, tickets_path??
Head First Rails is an old enough book that it’s probably not worth
studying. 2008??! That’s a
lifetime ago in computer programming, and rails changes faster than most
things in the programming world.
I understand now!
To generate a link in my RoR application I just need to prefix the word
“_path” with a controller name and it finds it.
That’s not necessarily true. You were on the right track to begin with.
The second argument to the link_to method can be a path. Rails will
create some paths for you and assigns names to them, like tickets_path,
which you can use as the second argument to link_to.
Rails also automatically creates some methods you can use:
ticket_path(@ticket)
which creates the path to a page that shows a particular ticket. But if
one of those ‘constants’ or methods actually produces the path:
‘/some_page’
You could just specify that path directly yourself:
<%= link_to ‘New Ticket’, ‘/somepage’ %>
The bottom line is: as long as your routes file maps a path to one of
your actions, it doesn’t matter how you obtain the path:
using one of the variables rails provides for you, e.g. tickets_path
using a method rails provides, e.g. ticket_path(@ticket)
specifying the path directly yourself, e.g. ‘/somepage’
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.