I have a model, blog_posts which has a field "published_at". I'd like to select the latest two blogs from that model to display on my homepage. Not sure how to structure that though.
At the moment I have a work around that takes a slice of the data but it keeps failing when I have nothing in the table, rather than fix this I feel there is probably a better way to retrieve the data.
I need to select the blogs in separate calls, for example
@blog_post.latestpost
, @blog_post.secondlatestpost
Is this what you're looking for? :
class BlogPost < Activerecord::Base
def self.latestpost
order("published_at DESC").limit(1).first
end
def self.secondlatestpost
order("published_at DESC").offset(1).limit(1).first
end
end
Use it like this :
BlogPost.secondlatestpost
or
BlogPost.latestpost
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With