A common functionality seen on many websites is to display a random testimonial from a client or customer of your product on a side bar or within the masthead, doing this in Rails is quite simple and is done with the assistance of a Rails helper and rendering a partial.
First off course you are going to need to generate your model within your command prompt/terminal insuring that you are in your projects directory:
script/generate model Testimonial
I’m expecting here that you are familiar enough with rails to create the migration file yourself and add a field for both the testimonial itself as well as the signature. Note Rails currently at 1.2.3 has an issue when using the name “quote” for a column name in your table.
Next let’s code the helper. In our helpers folder let’s open the application_helper.rb and add the following:
def show_random_testimonial
@random_testimonial = Testimonial.find(:first, :order => 'RAND()')
render(:partial => 'shared/random_testimonial', :object => @random_testimonial)
end
I like to put all my partials in a separate subdirectory in my views called shared.
Alright, so now create that shared directory in the view directory and create the file _random_testimonial.rhtml to use as our partial. Here we go:
<blockquote>
<p><%= random_testimonial.statement %></p>
<cite><%= random_testimonial.signature %></cite>
</blockquote>
You’ll notice above that I called my column for the testimonial itself “statement” which is a text field, and “signature” for the customer’s name which is a string/varchar. Now all you have to do is open up your layout file and call the helper <%= show_random_testimonial %> wherever you want your random testimonial to appear.
So that’s it. Until next time.