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?
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).
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:
Try to find the above in your local public libraries, they might have it. Otherwise, the Rails Guides does a good job.
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
)
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'