Rails Database Ease

19 comments | Posted: 6 March 06 in Tutorials, by Robert Evans

I am sure many of you have heard the hype about Rails and you may think to yourself, is it really that good..? To be honest, I also thought this when I first heard about Ruby on Rails. Programming that you really enjoy doing? Come on! No way! I like programming, but not enough to say it is something I find enjoyable to do. That was until I gave Ruby on Rails (RoR) a shot.

Intro

I had this project at work to create a custom Content Management System, or CMS, and I began writing it using PHP. After two weeks, or 90+ hours of coding in PHP, I was hating life. That is when I decided to check out Ruby and see if I could actually learn it while using it at the same time.

I had done a couple tutorials before, so, I started reading more about it and decided to get started with it for a day and see how it went. A day turned into a week a week into two and I had finished writing the backend of the CMS, all the while learning Ruby on Rails. I was impressed, to say the least. Not with myself, but with RoR.

Well, another two weeks later, I was done with the CMS. Better yet, I had a blast! Who knew…oh wait that is what they said about Rails, it’s fun!

That gives you intro to how I got into RoR. I am now reading everything I can get my hands on. Alright, this post is to give you a simple tutorial on the language/framework itself. I won’t be showing you how to write a blog or a to-do list, you can find those elsewhere written by more talent people than myself. I would like to start off talking about some of the basics of the Rails framework. So, it is less than a tutorial in the sense of showing you how to do something and more about sharing what I have learned with you. That being said, lets get going. Oh, and in RoR, I could have written all of the above in 1 line of code. ;)

The Simplicity of Rails when using a Database

I am going to talk about a few things to give you an idea of what Rails is like. For example, when you are writing a database driven website, and say you are using MySQL(My Structured Query Language), your database names need to be plural and your Rail models need to be singular. This is if you choose to have Rails manage the CRUD, or Create, Read, Update and Delete functions. You can always override these if you choose. For example, let’s say we have a database table called people, we should call our Rails model person. Rails is smart enough to know that person refers to people in the database. If you have a model named ruby, then you would name your database table rubies. If you had a database table named cameras, then your model would be named camera. I think you get the idea. But, what if you have a database table named item_numbers? Your model would be named ItemNumber. Rails also knows that two words put together, separated by a capital letter is really two words with an underscore attaching them both. Cool, huh?

Now, you can also override just about anything that is present in Rails. Let me give you a quick example of a SQL call to the database from one of our Rails controllers. Say we have this line of code:

camera = Camera.find(1)

This means Camera.find is telling Rails that you want to search the database table called Camera and you are looking for the id that equals 1, hence the (1) part. Well, what if you need a more specific call than this? Rails makes this simple. Ex.:

Let’s say our visitor fills out a form looking for a piece of information from our database. Let’s say you want to search for all the people who have a specific first name and age. First, we capture the data from the form doing the following:

name = params[:name]
age = params[:age]
person = Person.find(:all, :conditions => "name = '#{name}' and age = '#{name}'")

Now, the object person holds all the information found in the database that matches our conditions. Pretty simple, huh?

There are numerous ways to write your code to find specific information from the database. You can have Rails search the database and return the first row that meets your criteria by writing the following code:

person = Person.find(:first, :conditions => "name = '#{name}' and age = '#{name}'")

What if you want it to be ordered a specific way?

person = Person.find(:first, :conditions => "name = '#{name}' and age = '#{name}', :order => 'name DESC'")

The :order call is saying that I want the name to be in descending order.

What if you want more than 1 row, say 3 rows returned?

person = Person.find(:all, :conditions => "name = '#{name}' and age = '#{name}', :order => 'name DESC', :limit => 3")

Notice how I switched the :first to :all and then added :limit? You can set that limit to whatever you want. There are several parameters that can be used as well. A couple are offset and joins. Offset can be used in conjunction with limit, which allows you to specify the offset of the first row in the result set that will be determined by your find() method. Joins allows you to join additional tables to your default table.

There are also other methods that can be used besides the find() method. There is find_by_sql() where you can put actual SQL calls inside the (). There is another method that I found to be awesome. It is find_by_ method. Let’s say you have a database table call orders and you want to search within that table for a specific item. Here is how you could use the find_by_ method:

order = Order.find_by_item(:all, conditions => ["item = ?", "towel"])

You see how I put item at the end of find_by_? You can put whatever the name of your database is right there. Remember, it must be singular because Rails will look for the plural version. Now, I added something different to this call as well, the [“item = ?”, “towel”] part. The ”[ ]” shows we have a hash. The question mark is a place holder for that towel. So, what it is really saying is item = towel. You might ask, what is the point of having the question mark there, why not just put the towel string there. You could. You would just need to add single quotes around it.

The reason why this question mark is helpful is because you can put an instance variable there that is dynamic. This would allow you to allow the user to choose what item they want to see. This is how it would look:

item = params[:item]
order = Order.find_by_item(:all, conditions => ["item = ?", item])

Now it is more dynamic.

One last thing before I wrap this up. If you have a word that can be both singular and plural, like sheep, and your model is named sheep, Rails will look for sheeps. So, keep this in mind.

Conclusion

What I have show you here doesn’t even cover all the different types of calls you can do. These calls use the Active Record, that is a prebuilt class, which is part of the Rails framework. Do you see how easy it is to do your everyday database work? That is one of the things I love about Rails.

Note: If you want to read a very simple Ajax tutorial in Rails, go here: GodBit Forum covering RoR. It is something I learned how to do by reading the Rails Recipe book. It is not out yet, but you can buy the PDF version. I highly suggest it, as it has really helped me to understand Rails better.

Discuss This Topic

  1. 1 Yannick

    As I said over at your blog Robert, nice tutorial. Looking forward to more.

     
  2. 2 Nathan Logan

    Thanks a lot, Robert. Good stuff, here. You gave me the kick I needed to get re-interested in RoR – thanks!

     
  3. 3 Kyle

    Nice intro to ActiveRecord, which is an amazing tool. What you’ve shown is only 1/10th of it, it’s really a beautiful thing. The more I work with it, the more I find it’s genious.

    Although – if I may interject, it’s generally better to use this form when using user-submitted values:

    person = Person.find(:all, :conditions => [“name = ? and age = ?”, name, age]

    This allows Rails to do it’s escaping magic and prevent SQL injection. (As opposed to the #{var} method)

    Also, a nice helper on Rails’ pluralization can be found over at topfunky’s site: http://nubyonrails.com/tools/pluralize . Rails doens’t always pluralize by adding an s. It’s just that uncommon models (like Sheep) are generally not handled by the built in functions.

     
  4. 4 Yannick

    Hey Kyle,

    Nice of you to stop by and offer those additional details. That pluralize helper is really nice. Thanks for letting us know about it.

     
  5. 5 James Higginbotham

    Agreed – I am a full-time Java Architect and love working with Rails! I’m doing some exciting things with it, which I hope to announce in the coming weeks and months ahead on my blog. While I never liked PHP (I tried PHP 3.x back in “the day”) or Python, Ruby fits the bill nice and has a great deal of momentum behind it. Great to see your tutorial for those interested in getting started or just learning a little more.

    Oh, and I had the same reservations early on as well and then I just tried it! Wow!

     
  6. 6 Gareth Brown

    I must start to learn this stuff, thanks.

     
  7. 7 David Merwin

    If you are needing to stick with PHP instead of Rails, check out cakephp. Same methodology as Rails, but native to PHP. I have been using it to scaffold and test concepts, and I had a blog done in 15 minutes. Just like the rails tutorial.

    The best part for me as a developer… Cake is self contained and PHP dependent. Install the dirs and you are off and running. And, you do not need to install Ruby or fix it on the Mac ;-).

    http://www.cakephp.org

    You can see a great tutorial at http://www.grahambird.co.uk/cake/

     
  8. 8 Robert

    Kyle: I agree, this little bit I talked about doesn’t even come close to covering what Rails can do here. You are always welcome to interject and let people know that it is better to use the convention you showed. I should have added that in while showing the flexibility Rails allows the programmer.

    James: You will have to let us know what you are working on whe you decided to announce it.

    Gareth: You won’t be disappointed!

    David: PHP has a couple a descent frameworks like code ignitor, but the problem for me is that it is still PHP. For my thinking style, Ruby is very intuitive for me and PHP isn’t as much. The whole PHP vs. Ruby comes down to what you are really prefer and how your thought process works.

     
  9. 9 denny

    David, I’m curious. I currently work extensively with PHP…and have been interested in learning/experimenting with Ruby and Ruby on Rails. However, in everything I read, I read that Ruby is much slower than PHP. And several sites I’ve read seem to suggest that you should remain with PHP for any production-level sites. Can you provide any details from your experience on how you feel about the performance of Ruby and Ruby on Rails framework in relation to PHP?

     
  10. 10 Robert

    Denny: Ruby is here to stay. It is as old as Java, but just hasn’t had the attention Java has had till Rails has come out. If DHH has anything to say, Rails will also be here to stay. It has made such a huge impact that most all languages are mimicking it, which is why we see more frameworks being made today.

    The nice thing about Ruby is that it can do anything, where PHP cannot. PHP is a scripting language, Ruby can be used to develop desktop applications, video games, and web applications. In my opinion, Ruby is much more versatile than PHP.

    I haven’t really seen much where RoR, when setup correctly, is much slower than PHP. In many cases, I have seen RoR being faster than PHP.

    Ruby is just another language that is different than PHP in many ways. Rails is a framework for Ruby, to make Ruby programming quicker. It really all depends on what works for you and your project.

    All this backlash from PHP and Java developers against Ruby is quite ridiculous. It is like hating a palm tree because I have rose bush; it just doesn’t make sense. Same goes with Rubyist who hate PHP and Java.

    My suggestion is give Ruby a try, see if it fits your style and thinking. If it doesn’t, you only expanded your knowledge base, which isn’t a bad thing.

     
  11. 11 nate klaiber

    Nice article!
    I am looking to get into some RoR projects in the near future. I am/have been doing PHP for the past 7 years. I love it, and have no complaints whatsoever. No matter what the tool, if you use it in the wrong manner you can end up with crappy applications. Its a matter of preference, I like the freedom of PHP, but many (as you stated earlier) prefer the easier syntax of a framework (which are two different things). RoR could be compared to CAKEPHP, as Ruby could be compared to PHP – just as clarification to some.

    I have been playing with CAKE PHP as well, which handles database information in a nearly identical matter as you have listed.

    My main issue comes with this, and its present with most frameworks I have tested (even the new Zend release): I struggle with the database support. By that, I mean that you cannot get too complex with anything and still go the ‘easy route’. You end up having to use what you did in the first place. I normalize my databases, so my queried will be optimized – but the support for different join types and a naming convention is a barrier to me.

    No matter what, I am excited to check this out even further. Thanks for the great tutorial.

     
  12. 12 James Higginbotham

    Nate – I’ve found that ActiveRecord, the default Rails persistence API, provides enough flexibility to accomplish the typical normalized database. In addition, you can craft your own queries and have it map back into your models for more complex situations. It is lighter than an O/R tool and more flexible, though it works best if you are not connecting to a legacy schema. This is mainly due to its preferring table naming conventions, though you can tell it what you want.

    There are other persistence APIs as well as AR that work with Rails, though AR is the most commonly used. Rails 1.1 will have some nice features that will further enhance supporting normalized schemas and should be out soon.

    While anything done right is often divergent from the ‘easy route’, Rails is a little easier than dropping to Java + Spring + Hibernate, definately more productive, and great for most needs except the most performance-intensive applications (financial engines, for example). I think Bruce Tate put it best when he said (paraphrase), “While some scripting frameworks let you get things done quick and dirty, Rails lets you get things done quick and clean.”

     
  13. 13 Robby Russell

    In your conditions… try to avoid using:

    :conditions => “foo = ’#{bar}’”

    SQL injection…. friendly

    Use placeholders!

    :conditions => [ ‘foo = ?’, bar ]

    or even better… named placeholders:

    bar_hash = [ :foo => ‘meep’, :tea => ‘green’ ]
    :conditions => [ ‘foo = :bar AND tea = :tea’, bar_hash ]

    ...much safer. :-)

     
  14. 14 Paul H

    Thanks for the RoR article, if I was a full time php/mySql developer I think it would be enough to get me to try it. I have been reading about RoR for a while but have struggled to find any absolute beginners tutorials. Can any body recommend one?

    I have been to the official RoR site but even there all of the language and descriptions assume far more knowledge than I currently possess. By contrast I am making good mileage with OReillys Learning PHP 5 and a bunch of websites that help the xhtml/css developer upgrade to dynamic sites using php/mySql. Ruby on Rails might be easier and cleaner than php, but thats hypothetical if I cant find a way to get started. Hope you folks can point me in the right direction.

     
  15. 15 Robert

    Hey Paul. I would suggest grabbing a copy of Agile Web Development with Rails. It is a great resource for beginners to the Rails framework and doesn’t assume you have a working knowledge of the Ruby language.

    If you could give me more detail of why type of information you are looking for in a tutorial, I can write one up in the next week or so here on Godbit. What types of things from the RoR sites made things difficult to grasp? Were you looking for more of an explanation of syntax, or reasons why certain calls were made? Are you looking for something to walk you through building an application or something that just talks about the framework and the language itself? Or both?

    Give me a bit of feedback and I will see what I can come up with in the next week.

     
  16. 16 Robert

    Robby: Thank you for pointing that out.

    My intention for this writeup was to show the flexibility of Rails, not the best practices or which method is better for whatever reason. It was more of an introduction to database interaction using the Rails framework and how easy and flexible it is. Basically, the same concept that you can find in the Agile Web Development book.

    In the future, I will make sure to cover best practices with my introductions to various aspects of the Rails framework.

     
  17. 17 Paul H

    Hi Robert. Thanks for the pointer to Agile Web Development with Rails, I will take look at it. I bought a copy of the Pickaxe last year which had a lot of theory that made sense, maybe the Agile book would give me a few things I can practically use (to build dynamic web sites) and is the ROR start I need.

    That’s a generous offer to write up a beginners tutorial for me! Makes me feel I should choose carefully… I guess what I need is to be walked through doing something fairly simple, with an explanation of what I am doing on the way. Perhaps how to make a dynamically generated web page that pulls its text content from a mySql database. Something to get the learning process started, maybe with an explanation of any words you use that I will not have come across using html/css/php/ecmascript. If that is too much of a big ask then please do scale it down to something smaller that can show up in my browser.

    For now I just need a start. In the future I might want to create SVG with AJAX communication using ROR, and can imagine following your footsteps by building my own CMS for web sites, but perhaps not all of that next week :-)

    Cheers, Paul

     
  18. 18 Robert

    Ok Paul. I will put together a tutorial on how to build a single web page that will pull information from a MySQL database. I’ll add a bit on how to add information from that web page to the database as well. That way you can see both processes of input and output using RoR and the DB.

     
  19. 19 Mark

    Hey Paul – why not work your way through ‘Four days on Rails’ (actually can be done in a day…).

    It brings you through creating a ‘to do’ list application and explains the nitty gritty of everything along the way (with direct references to the API documentation)

    Really, really good place to start – then go to the Agile book.

    You’ve got to love the pragmatic programmers!

     

Comments closed after 2 weeks.