Search code examples
ruby-on-railsscaffolding

Auto generated code via scaffolding in Rails


I am trying to follow along some scaffolding code in Ruby. The scaffolding was generated like this:

rails generate scaffold Person name:string

Now when I look at the generated code in some of the xxx.html.erb I see references to edit_person_path() as in the example below in the case of show.html.erb. Can somebody set me straight on what the edit_person_path() is and how/where it comes into existence? I played around a bit and printed out the output from edit_person_path() and see that it returns /people/id/edit (where id = actual integer). Deducing from this I am thinking edit_person_path("x") returns /people/x/edit but need to understand more of this black magic.

<p id="notice"><%= notice %></p>

<p>
   <strong>Name:</strong>
   <%= @person.name %> 
</p>

<%= link_to 'Edit', edit_person_path(@person) %> |
<%= link_to 'Back', people_path %>

Solution

  • Totally white magic here. Those are helpers Rails uses in order to generate paths and URLs automatically: http://guides.rubyonrails.org/routing.html#path-and-url-helpers.

    For example, if you generated scaffold Person, you are going to have automatically the following helpers available:

    people_path() # /people, because rails uses 'person'.pluralize
    new_person_path() # /person/new
    edit_person_path(@person) # /person/:id/edit
    person_path(@person) # /person/:id
    

    etc.