SupremeA
SupremeA

Reputation: 1621

Call an instance by most recent dates rails

I have a set of blog post and I want to display them in order of most recent date. How can I call that method in the controller

I tried

@post1 = Post.last

but how would I do the 3 previous to this one?

Upvotes: 1

Views: 37

Answers (2)

mu is too short
mu is too short

Reputation: 434835

This:

@post1 = Post.last

doesn't give the last Post in the way you think it does. If you check your logs you'll see something like this:

selector={"$query"=>{}, "$orderby"=>{:_id=>-1}}

so it will be "last in id order", not the last by date. If you want the last by some timestamp then you have to say so:

@post1 = Post.order(:created_at => :desc).first

You'd use some other date or timestamp instead of :created_at if you have one that better matches your intent.

Now, if you want the three previous to that, grab four and throw one away:

other_three = Post.order(:created_at => :desc).limit(4)[1.3] # or any of the ways

Or you could use offset to skip the first one:

other_three = Post.order(:created_at => :desc).offset(1).limit(3)

Upvotes: 1

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34338

This should give you what you want:

@post1 = Post.last(4).reverse[0..-2]

Post.last(4).reverse will give you last 4 records in descending order. And, then with this: Post.last(4).reverse[0..-2] you are grabbing all but the last element which is what you want.

If you don't want the descending order, then you can just do this without the reverse part:

@post1 = Post.last(4)[0..-2]

Hope this helps.

Update

You can also do it this way:

@posts = Post.limit(4).order(updated_at: :desc)[1..-1]

Upvotes: 0

Related Questions