Name my buck

I got this buck from my wife for Christmas. We like to shoot at it.

Name my buck

The results so far...

  1. Uncle Buck
  2. Buckerle
  3. Buckmeister
  4. Ed
  5. buckminster
  7. <a href="http://localhost" onclik="alert('ok)"></a>
  8. Poop McGee
  9. Buckweiser
  10. @
  11. [
  12. ''
  13. 8
  14. labo_soanata
  15. Buck yeah
  16. Buckington
  17. Motherbucker
  18. glowy

How did that happen?

First we have a model to store in our database called BuckName. It inherits everything from the ActiveRecord class, which has all we need to create objects and save them to the database.

Ruby code

class BuckName < ActiveRecord::Base

Now that we have the model, we need a controller to do the magic behind the page. The view passes parameters to the controller, which updates the instance variables available in the view logic. We can pass the name to the controller, and the controller sends back all your bucks in instance variable @bucks.

class BuckController < ApplicationController

  def index
	# this is the name that gets passed in
	name = params[:name]
	# see if we got a name
        if name and !name.blank?
	  # see if we have this name
	  buck = BuckName.find(:first, :conditions => {:name => name})
	  if buck
	    # we have this name, add a vote!
	    buck.votes += 1
	    # we need to create a name and add a vote
	    buck = BuckName.create({:name => name, :votes => 1})
          # let them know who they voted for
          flash[:notice] = 'You voted for ' + name
	# sort the bucks into an instance variable
	@bucks = BuckName.find(:all, :order => 'votes DESC')
  def set_title
    @title = 'Name my buck'

Now we only need to iterate through @bucks, which the controller has carefully sorted by the number of votes. Ruby has a fun iterator for this, each do

@bucks.each do |buck|
  # do something with buck

Rails code

The rails is pretty easy from here, don't you think?

<h1>Name my buck</h1>
<p>I got this buck from my wife for Christmas. We like to shoot at it.</p>
<img src="/images/buck.jpg"> </br>
<% form_tag :action => 'index' do %>
  <p>Name my buck
  <%= text_field_tag 'name', @name %>
  <%= submit_tag 'Vote' %></p>
<% end %>
<h2>The results so far...</h2>
<% @bucks.each do |buck| %>
  <li><%=h %></li>
<% end %>