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. default
  5. Ed
  6. reassuringly
  7. buckminster
  8. Impossiblebucker
  9. glowy
  10. Buckweiser
  11. Poop McGee
  12. <a href="http://localhost" onclik="alert('ok)">www.google.com</a>
  13. http://www.google.com
  14. @
  15. [
  16. ''
  17. 8
  18. labo_soanata
  19. Buck yeah
  20. Buckington
  21. Motherbucker

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
end

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
	    buck.save
	  else
	    # we need to create a name and add a vote
	    buck = BuckName.create({:name => name, :votes => 1})
	  end
          # let them know who they voted for
          flash[:notice] = 'You voted for ' + name
	end
	
	# sort the bucks into an instance variable
	@bucks = BuckName.find(:all, :order => 'votes DESC')
	
  end
  
  def set_title
    @title = 'Name my buck'
  end
  
end

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
end

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 %>
<p><b>
<h2>The results so far...</h2>
<ol>
<% @bucks.each do |buck| %>
  <li><%=h buck.name %></li>
<% end %>
</ol>
</b></p>