Birds on Rails, Part 2
Rails seems to be installed and working (Finally. That took almost a full day.) so let’s see if we can build some real pages. The first thing I need is something simple. I want to iterate through the sites table in the database and print each name in the site into an HTML unordered list. The SQL command is as follows:
SELECT name FROM sites
(It will be a little more complex in the future, but let’s start simple and add to it.)
Rails embeds Ruby code in HTML using <% %>
and <%= %>
markers. Here’s another downside. This is not well-formed XML. PHP correctly uses processing instructions for this. Rails should have copied from PHP instead of JSP/ASP.
So I went ahead and added this chunk of code to the index method that’s creating the main page by calling render :text
.
<% @sites.each do |site| %> <li><%= site.name %></li> <% end %>
Hmm, that completely didn’t work. Apparently I first need to create a view. That is, I need to create a file called index.rhtml
in the app/views/bbr
directory. Then I need to delete the index
method in the bbr_controller.rb
file. Then I put my Ruby code into the index.rhtml
file instead. Then in bbr_controller.rb
I put this code:
def index @sites = Site.find_all end
This maps the sites
variable to the sites table so I can reference it in the view rhtml file. And voila. The index page now pulls the list of site names out of the database and inserts them into the web page as desired.
November 30th, 2005 at 4:45 PM
Why do you think not having well-formed XML templates is a downside?
Just curious.
November 30th, 2005 at 5:08 PM
Because I can’t work with them using XML tools, of which there are many useful examples. No schemas. No stylesheets. No SAX, DOM, or XOM. No XML editors. It’s pointlessly locked out of a valuable ecosystem. :-(