views:

79

answers:

4

I am teaching myself rails (coming from PHP for web apps) and I can't find any good docs to help me. But I was wondering how would you tell your method to take the last post(controller is post) in the database? I tried Post.find(:last) but that did nothing sadly. Anyone know?

A: 

guide.rubyonrails

railsbrain

There's a few links to start you off.

Are you sure there are posts saved to the database? That method should work if you have a Post model (the model name should be singular).

inkdeep
A: 

I believe the following should do the trick assuming you have a Post model object:

Post.find(:all).last

I'm learning Rails too and I'm following the book Simply Rails 2. These other two books are also recommended for Rails dev:

  1. Agile Web Development with Rails
  2. Rails for PHP Developers

Try to find the above in your local public libraries, they might have it. Otherwise, the Rails Guides does a good job.

Thierry Lam
Careful with that statement as it loads *all* Posts from the DB and then returns the last one. "Post.last" is the proper call.
Matt Darby
+2  A: 

Try Post.last. It's shorter.

But as inkdeep said, be sure you have posts in the DB to begin with. Try this:

Post.create :title => "Boring Title", :body => "Blah Blah Blah"

(assuming you have title and body columns)

create does a one-step object instantiation and save (be warned--Post.new doesn't save anything to the DB, you need to explicitly .save)

zenazn
A: 

You have two common solutions depending on your needs:

Post.find(:first,:order=>'id desc') #It's slow in MySQL
Post.find(:first,:order=>:created_at) #You have to add the 'created_at' field but it gets updated 'automagically'
Fer