NoobOnRails

Ruby on Rails tips, tricks and hints for the aspiring rails hero.



Wednesday, November 30, 2005

Because to use Rails, you need to learn Ruby


If you do nothing else today, take 15 minutes and run through _why's interactive Ruby tutorial, Try Ruby! Life will seem so much better after doing so.

Tuesday, November 29, 2005

Dynamically setting the page title


Don't you hate manually editing the title tags for more than one page in your website? I used to. Ruby on Rails makes changing your page titles a bit easier to manage. In your layout, throw in

<%= @page_title || "your_default_app_title_here" %>

in betwteen your title tags. Now on any .rhtml page in which you don't want "your_default_app_title_here" to be the title, set the @page_title variable.

For example...

<% @page_title = "this page makes me happy with glee" %>

...Heck, say you got an incoming params you want to show up in the title, do so with a little...

<% @page_title = "tagged with #{params[:title]}" %>

...Voila! Magic. (for uber noobs, you gotta use the #{} to use ruby code in a string, if this wasn't in the <% %> tags and just in some text on the page itself, all you would need to do is (for this example) <%= params[:title] %> ...

Monday, November 28, 2005

Good Ruby on Rails site for Rails noobs


If you have a Ruby on Rails question or you've figured out something you've been tinkering for a while and think other Rails noobs could benefit from your generous sharing, head on over to RailsWeenie! No question too noob, no tip too 1337. Help out aspiring Rails heroes worldwide by just getting involved. You know you want to.

Sunday, November 27, 2005

Don't use "Test" !!!


When building your app from scratch, don't use "tests" as a name for any of your database tables or for any actions. It seems to be a reserved word and not using it from the get-go can save you a lot of time.

Friday, November 25, 2005

Rails noob to Rails pro in 17 sites or less...


Figured I would put together a list of the Rails tutorials that have helped me learn RubyOnRails.

0. Curtis (fine first name I may say) Hibbs wants you to know Rails. "What Is Ruby on Rails" - Excellent intro to Rails article that covers the main Rails components, what they are and how they integrate.

1. Curtis Hibbs hearts Rails, soon you will too. "Rolling with Ruby on Rails". No better way to learn a new language than buy digging in and building an application with it. In 5 pages no less.

2. Curtis Hibbs part deux. "Rolling with Ruby on Rails, Part 2" - Digs in a little deeper than part one. By the end of this one, you have a decent working application. In the process, you kind of get an idea of how Rails works.

5. Return of Curtis Hibbs. "Ajax on Rails" - Gives you some insight into one of the many things that Rails does well. Making ajax dead-simple. Script.aculo.us deserves some credit on the whole "making ajax dead simple" vibe since they're really the javascript library that ties dirty ajax into a nice simple package easily integrated into the RubyOnRails framework.

6. Amy Hoy is my hero. "Really Getting Started in Rails" - Goes deeper that Hibbs' tutorials. Gets into the somewhat gritty details of Rails like how variables are formatted and how Rails like it's database tables to look.

7. Amy Hoy on MVC. "MVC: The Most Vexing Conundrum" - In this article, Hoy sheds some light on the whole Model-View-Controller structure of RubyOnRails. Helpful if you're new to the MVC way.

8. RoR wiki itself. "GettingStartedWithRails" - Good starting point for experienced developers who want to get rails up and gunning on OSX or Debian or Gentoo or Fedora Core or FreeBSD or OpenBSD or even Windows.

9. RoR site comes through. "How to make a todo list program with Rails 0.9 (out of date)" - Even though it's "outdated", this tutorial will help you build a basic to-do list program pretty quickly.

10. IBM (?) digs RoR. "Fast-track your Web apps with Ruby on Rails" - IBM walks you through building a pretty basic "Address book" app while giving you some information on how Rails interacts with your database.

11. Webmonkeys sip the Rails kool-aid. "Getting Your Feet Wet With Ruby on Rails" - Good intro to Rails (with a dash of Ruby) webmonkey style.

12. "Four Days on Rails" - An overall good tutorial that covers a lot of Rails functionality. A bit dated but still a good way to learn more.

13. Cnet even. "Ruby on Rails chases simplicity in programming" A good look at the how and why Rails came to be.

14. Official RoR FAQ. "FAQ" - A good fact that will point you where you need to go when you begin to start making sense of things.

15. Making it public. "The Perfect Rails/Debian/Lighttpd Stack..." Good guide to getting your "production-ready" app up and running in the aforemention configuration. Want to get up and running on Apache 2+? Check here.

16. Think you're finally beginning to get it? Let the RubyOnRails api docs put you in your place. While not for the faint of heart, this will eventually become the place to go once you've acquired some RoR skills from the above sites.

17. Since you'll eventually have to learn Ruby to become a Rails Hero. "Why’s (Poignant) Guide to Ruby" Poignant and just entertaining. This will give you the lowdown on the Ruby language itself. You'll need a good grasp on this to get into the more advanced Rails adventures.

Overall, these sites should be more than enough to get you going. Soon, you'll be churning out apps like nobody's business. If (or more likely when) you run into a snag, be sure to check the oh so helpful mailing list or the irc chat room.

Happy Railing!

Wednesday, November 23, 2005

The first Rails studio is done


Looks like the first Rails studio has come to an end. Looks like everyone had a good time jammin on rails. Looks like it was a pretty packed room. If you're a noob who wants to learn the ins and outs of rails, Mike and Dave may be having another studio session soon. You'll need to act fast, the last one sold out pretty quick from what I remember.

Monday, November 21, 2005

Prim and proper dates


Since Rails will automatially maintain "created_on" and/or "updated_on" fields if you create them in your database, most everyone adds them (by most everyone I mean myself and....well, no....just myself). Having these date fields is all fine and dandy but honestly,

Fri Nov 18 00:10:53 Mountain Standard Time 2005 (FNMST for short)

aint gonna cut it in today's ajaxed,web-two-dot-oh world. So, how do you make your dates look decent enough to be normal? Why with .strftime() of course. Say you have a created_on datetime field in your database and you're calling it in a view with a little

<%= book.created_on %>

action. Purty it up by adding strftime like so:

<%= book.created_on.strftime("%m-%d-%y") %>

I bet you already figured out what the m, d and y stand for. If not, for shame! Fret not though, you do have more options to choose from, here's a list I found in the Ruby documentation (in the help files actually)

Time#strftime directives
Format Meaning
%a The abbreviated weekday name (``Sun'')
%A The full weekday name (``Sunday'')
%b The abbreviated month name (``Jan'')
%B The full month name (``January'')
%c The preferred local date and time representation
%d Day of the month (01..31)
%H Hour of the day, 24-hour clock (00..23)
%I Hour of the day, 12-hour clock (01..12)
%j Day of the year (001..366)
%m Month of the year (01..12)
%M Minute of the hour (00..59)
%p Meridian indicator (``AM'' or ``PM'')
%S Second of the minute (00..60)
%U Week number of the current year, starting with the first Sunday as the first day of the first week (00..53)
%W Week number of the current year, starting with the first Monday as the first day of the first week (00..53)
%w Day of the week (Sunday is 0, 0..6)
%x Preferred representation for the date alone, no time
%X Preferred representation for the time alone, no date
%y Year without a century (00..99)
%Y Year with century
%Z Time zone name
%% Literal ``%'' character


Enjoy!

Saturday, November 19, 2005

Using acts_as_taggable in Rails (quick reference)


Here are the quickfire steps to use the acts_as_taggable gem...

1. In your project database, add two tables, tags and tags_[model you're linking to], here's an example sql script:

CREATE TABLE `books` (
`id` int(6) unsigned NOT NULL auto_increment,
`title` varchar(50) NOT NULL default '',
`author` varchar(50) NOT NULL default '',
`description` text NOT NULL,
`created_on` datetime NOT NULL default '0000-00-00 00:00:00',
`updated_on` datetime NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `tags` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(30) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `tags_books` (
`tag_id` int(11) NOT NULL default '0',
`book_id` int(11) NOT NULL default '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. at a command prompt, from in your project directory, run

gem install acts_as_taggable

3. Add this line right above the end in your environment.rb

require_gem 'acts_as_taggable'

4. Create a tag model. You can do this manually or with the generator like so:

ruby script\generate model Tag

5. In your target object's model.rb file (books.rb in this case) add

acts_as_taggable

6. In your target object's controller (books_controller.rb for us) add this line under your
if @books.save line..

@book.tag(params[:tags])

7. Add this to your _forms partial

tags for this book: <%= text_field_tag('tags', '') %>

8. To get the items to show in yor list.rhtml view, you can call them with this

<%= book.tag_names.join(" ") %>

That's the quick way to get acts_as_taggable working. For more functionality, check this out.


Friday, November 18, 2005

Using acts_as_taggable in Rails (for the uber noobie)


If you're up on web trends, you know how cool having the ability to tag items on your site makes you look. Cool enough to wear shades in doors. You'll be glad to know that, true to the Ruby and Rails way of keeping things simple, adding tag finctionality isn't too bad. Dema wrote up a little mixin called acts_as_taggable which makes tagging in rails a lot eaiser to do. It started out as a mixin but it's now a gem so installing it is a snap, just run this from a command prompt (from inside your app folder, you don't have to do this now)...

gem install acts_as_taggable

and you're off and running.

Let start with a brand new app. Inside the folder of your choice, run...

rails books

...to get the app's basic structure laid out. After Rails creates the structure and it's all laid out, pop over into your ...\Book\app\config\ folder and edit your database.yml file. Were going to be doing all of our work in development mode so you need to only work with the development section. Edit it to fit your environment. I'll be using MySql so my development definition looks like this:


development:
adapter: mysql
database: books_development
username: root
password: root
socket: /path/to/your/mysql.sock


In your books_development database, we're also going to .


CREATE TABLE `books` (
`id` int(6) unsigned NOT NULL auto_increment,
`title` varchar(50) NOT NULL default '',
`author` varchar(50) NOT NULL default '',
`description` text NOT NULL,
`created_on` datetime NOT NULL default '0000-00-00 00:00:00',
`updated_on` datetime NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `tags` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(30) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


CREATE TABLE `tags_books` (
`tag_id` int(11) NOT NULL default '0',
`book_id` int(11) NOT NULL default '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Copy this into a text file and save it with a .sql extension and import it into your book_development database. If you need help on that, open the MySql command line client and type in \h for help.

Now our database structure exists so lets do some scaffolding since it's so easy. From inside your app directory (for this case, in the Book folder) from a command prompt just run

ruby script\generate scaffold Book

At this point, you could go ahead and run...

gem install acts_as_taggable

...inside your app folder to install the required gem. As far as I can tell, you'll have to do this for each app you want to use this gem in. After that's done, let's test it and make sure everything is up and running. Start webrick (run ruby script\server from inside your app folder) and take a look at your site. My url was http://localhost:3000/books, yours should be something simliar. Go ahead and create some books to make sure everything is working so far.

After you have some data and you're chomping at the bit to get to tagging, add (manually type it in, don't copy and paste it from here)

require_gem 'acts_as_taggable'

...right above the end in your environment.rb (in your books\config\ folder). Since we edited the emvironment/rd file, you'll need to ctrl+c your webrick instance (on Windows) to stop it and then bring it back up. Now you need to create a Tag model. Running...

ruby script\generate model Tag

...will do. You don't need to anything in it yet, but it needs to exist for this to work. Next, hop over to your book model and add

acts_as_taggable

We're getting closer. You now need to pop into your books_controller and save the tags params inyour database. Open your books controller and look at the create method. More specifically, the first few lines...

@book = Book.new(params[:book])
if @book.save
flash[:notice] = 'Book was successfully created.'

You're probably thinking (at least I know I did), shouldn't the Book.new(params[:book]) be gathering all the data from the form? The problem is, the join table we created (tags_books) links the book id to the tag id, how can they be linked if the book.id doesn't exist yet? They can't, so you need to @book.save first so that the book record can be created and be assigned a book.id. Then you can save the tags. So instead of the above, it needs to look like this...

@book = Book.new(params[:book])
if @book.save
@book.tag(params[:tags])
flash[:notice] = 'Book was successfully created.'


...that should do it. Now or models are ready and our controller is ready. Now we need to work on that view. Let's start with the _form.rhtml partial in your app\views\books\ folder. Both the new.rhtml and edit.rhtml point to this partial but we won't worry about how to edit them just yet. Right now, we just want to be able to add a new book with some tags. To do so, edit your _form.rhtml partial to look like this...





...you can stick that "tags for this book" line wherever you want in this partial and you should be good. Refresh and take a look at your http://localhost:3000/books/new page to see the new field. Test it out and create a new book with a tag or two. To enter in more than one tag, just add a space between them. After you save your tagged up book, you'll notice that it'll get created successfully and the data ends up in your database, but no tags show up on your list page. Time to tackle the list.rhtml view. Open that up and edit it so it looks like this...




...the book.tag_names.join(" ") is the code that pulls our tags out of the database, use a space to seperate them. Congrats, you know have some basica tag functionality going on. Check out Tagging on Steriods with Rails , the acts_as_taggable rdoc documentation as well as the actual rubyforge page for more info. I'll also put up a post with just the steps listed so you have an easy refernece point to refer back to without having to read this whole post again.



Howdy


Hello and welcome to NoobOnRails. I'll be throwing up some posts every now and again for the Ruby on Rails Noobie who is trying their dardest to learn Rails and could use some help from time to time. I am a rails noob myself so as I figure things out, I'll post on how certain aspects of rails works, from teh noob's perspective.

All you pros out there feel free to jump in and set us straight. I know I am going to need it from time to time. So let's begin with some Tagging action with a look inside the oh-so hip gem, acts_as_taggable.


in case you're wondering...

Why did i choose blogspot and not typo? Simply because my budget is less than nil and blogspot is free. boo yah.

also...

no this isn't pink, it's a kinder, softer shade of red...ruby red baby!