Welcome to Working With Rails


Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
fetching :last from post.comments
3 Posts
fetching :last from post.comments


After some time building my site, i stumble again on some part of my comments. am a bit confused on why, for example this line


will succeed in my development server. however, on a production server, i get an error that i don't have a method of a 'user'. ok, i got the idea on why. first, i really don't have a variable/method for that. but on dev server, i can fetch a 'Post' with a last 'Poster' with no error.

is there any other way, i can fetch a Post, with a Last Poster on it's side?, like i was doing a simple forums with set of details on the index.

here's what i have been doing exactly, i have an association of Posts that has_many comments, and a User that has_many comments, a simple association.

on my comment model: def last



for the controller, just some simple find method

my code in my template.

is there a way i can simplify this and make this work on a production server?

Thank you again!. have a good day.

I'm not entirely clear on what you want to do, but I suspect your missing method problem is simpler than you think. In your example code:


you don't handle the case of a post with no comments. Calling #last on an empty collection will return nil, which has no #user method. That's probably the error you're seeing.

On an unrelated note, your later example for your Comment model:

def last find(:all) # I assume you mean this to be find(:all).last end

is very much not what you want to do. Firstly, Rails provides a #last finder method, so there's no reason to reimplement it. More importantly, this will fetch far more from the database than necessary. This will return all matching rows and create ActiveRecord objects in memory for each of them, all but one of which will sit around unused until the garbage collector gets around to them. If you have enough processes doing this at once you can easily bring down a server.


how come i did not realize that, calling a #last on an empty collection will return a nil, that's the error i am seeing. i have a post that has no comments.. maybe needs some more study :D and yes, i mean to say def last find(:all).last end i quitted that, and just use the rails #last method :D

thank you very much again Adam, you always saves Me :D you're the best!!

3 Posts
Login to add your message