Friday, August 30, 2013

Limiting loop for array of objects in Rails


While fetching records from DB, we can definitely limit the number of records to fetch as following.
@post.comments.limit(10).each do |comment|
   comment.description
end
But in practical, sometimes we face that we have an array of objects fetched from DB and we want to access first or last few objects. Using following code we can easily solve it. 

Reading first 10 records -
@posts.first(10).each do |post|
   post.title
end
Reading last 10 records -
@posts.last(10).each do |post|
   post.title
end

No comments: