A Ruby on Rails partial can be thought of as a kind of view-function. When a partial is created it is given a name and collection of data, such as an array. The code inside the partial template will then be repeated for each element of that array, and that array element can be accessed by the name of the partial inside the template.
This tutorial was created with Rails 3.0.5. To find out which versino of Rails you are using type: rails -v.
Let's start from scratch and create a simple rails application:
-create new rails app called 'partial_test' rails new partial_test -generate MVC for 'item' record rails generate scaffold item name:string serial:integer -update database with item model rake db:migrate
The above commands will create CRUD functions for a record called item. Each item has a name and a serial number. These commands will also create an items index, which is where we will create our partial.
If you make a mistake, the following commands may be useful.
-delete MVC for items rails destroy scaffold item -undo the last migration rake db:rollback -reset the database and re-run all migrations rake db:reset -completely clear the database rake db:drop
Once the application has been created we can run it with:
rails server
We can access our items index at:
http://localhost:3000/items
Add 3 test items
Use the add page to create 3 test records. Our goal will be to replace the code in the index.html.erb file with a partial function.
/app/views/items/index.html.erb
| Name | Serial | |||
|---|---|---|---|---|
| <%= item.name %> | <%= item.serial %> | <%= link_to 'Show', item %> | <%= link_to 'Edit', edit_item_path(item) %> | <%= link_to 'Destroy', item, :confirm => 'Are you sure?', :method => :delete %> |
Once our partial template is created, we can replace all of this code with:
Listing items
<%= render(:partial => "item", :collection => @items) %>
<%= link_to 'New Item', new_item_path %>
This partial is named 'item', and like all partials, it's template file must be prefixed with an underscore _
/app/views/items/_item.html.erb
<%= item.name %> <%= item.serial %> <%= link_to 'Show', item %> <%= link_to 'Edit', edit_item_path(item) %> <%= link_to 'Destroy', item, :confirm => 'Are you sure?', :method => :delete %>
This is the code block that will be repeated for each element in the array @items. Each item in that array is accessed by the name of the partial, not the name of the array.
In this example, we significantly cleaned up our view and abstracted away the foreach loop. This is just a basic example of ruby on rails partials. There is much more that can be done with partials. Partials can call other partials and set the framework for AJAX powered rich internet applications.
You might also be interested in





