Learning Ruby and Rails. In following the getting started guide if I invoke
rails generate scaffold Post name:string title:string content:text
it generates among other things code like the following in index.html.erb:
<% @posts.each do |post| %>
<tr>
<td><%= post.name %></td>
<td><%= post.title %></td>
<td><%= post.content %></td>
<td><%= link_to 'Show', post %></td>
<td><%= link_to 'Edit', edit_post_path(post) %></td>
<td><%= link_to 'Destroy', post, confirm: 'Are you sure?', method: :delete %></td>
</tr>
<% end %>
</table>
My only concern in the above is edit_post_path, and my question is, what is it – and specifically from a Ruby standpoint. It certainly has every appearance of being a Ruby method, and its embedded in other code which is most definitely Ruby: posts.each do |post|...end that’s all Ruby
But if edit_post_path is a Ruby method, where is the code for it? ‘post’ is a label I have provided to Rails, so presumably this Ruby method should be somewhere in my site directory along with other Ruby code generated when invoking “rails generate scaffold…” above (i.e. it wouldn’t be in a Rails-specific directory for example). But there is no such method ‘edit_post_path’ defined anywhere. So is it not really Ruby at all, just something contrived to look that way for some reason, and really just a string of text that is processed by something strictly proprietary to Rails. Is this an example of what is so cool about Rails?
That is a Rails helper method – aka
sugarsyntax as James pointed out – for routing within your app.To see all the routes available to you, at the command line do
rake routes. You will see a list of the helpers on the left, then you will see the HTTP operation in the second column, third column = URL path format, and last column is a breakdown of the controller and action that it relates to.To see some of the Ruby code that is at the heart of this
magic, check it out in the Rails 3 repo, like this: https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/routing/mapper.rb#L444Also if you want to create custom URLs for specific resources, check out: https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/routing/url_for.rb
Here is some more info on routing in general: http://guides.rubyonrails.org/routing.html
Hope that helps.