Re: Issue displaying user posts

Matt Jones
Sun, 29 Nov 2009 18:47:54 -0000

On Nov 28, 3:11 pm, RubyonRails_newbie
<craigwest...-gM/Ye1E23mwN+BqQ9rBEUg@public.gmane.org>
wrote:
> ** RESOLVED **
>
> If anyone else experiences something like this,
>
> Original line of code: @posts = Post.find_by_user_id( session
> [:user_id], :order => "created_at DESC")
>
> change it to:
>
> @posts = Post.find_by_user_id( @user.id, :limit => 1, :order =>
> "created_at desc")

Note that the preferred way to do this is from the other side of the
association:

@user.posts.find(:first, :order => ''created_at DESC'')

or even to define a ''recent'' scope on Post:

named_scope :recent, :order => ''created_at DESC''

and then the line in the controller reduces to:

@post = @user.posts.recent.first

--Matt Jones

--

You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk+unsubscribe@googlegroups.com.