contact

Super simple Ruby on Rails how-tos

Enjoy this article? Share it with others.

Bookmark on del.icio.us Bookmark on Design Float Bookmark on Digg Bookmark on Google Bookmark on Slashdot Bookmark on StumbleUpon Bookmark on TwitThis

A few bits of helpful code for Ruby on Rails developers.

I’ve just started learning Ruby on Rails. Its great, but frustrating. The object orientation, syntax, and models are all new to me. It seems to take forever how to figure out something that turns out to be one line of code. That said, here are some really simple how-tos.  Note: these apply to Rails 1.2.6 and before.  Rails 2.0 has new RESTful conventions.

Link to a different controller than the one you’re currently in

 <%= link_to "Classified ads!", 
{ :controller => 'controller_name',
:action => 'action_name' } %>

Redirect to a different controller than the one you’re in

 redirect_to :controller => 'home’' :action => 'index'

Get some records from your database, and display them in a div somewhere

In your model (mine is called "Bookmark"), get some records. This code gets the record with the highest id, just for testing. It will work with multiple records just the same.

def self.recent_item
  return Bookmark.find(:all, :order => "id DESC", :limit => 1 )
end

In a view, or preferably a partial, loop through the results

<% for item in Bookmark.recent_item %>
  <p><%=h item.description %></p>
<% end %>

That’s it!

-Ben Seigel, owner, exp design