How to add two arrays together AND run methods on them to order, limit, or paginate
Im trying to make a news feed for a site and Im adding two arrays of different classes together to create a @feed_items array. But clearly I need to be able to order the new array by created_by
right now I have:
def home
@comments = Comment.all
@images = Image.all
@feed_items = @comments+@images
end
So right now when I loop the @feed_items in my view, the loop displays all the comments (ordered by created_at), and then i开发者_如何学Ct display the images(ordered by created_at). But I need to order the entire array so everything is mixed up and ordered correctly.
I tried to do this:
def home
@comments = Comment.all
@images = Image.all
@feed_items = (@comments+@images).order('created_by DESC')
end
But I get an undefined method error for the @feed_items array. Same thing with tying to use limit or paginate.
If you can't do it in SQL, which is the case when you're dealing with two different tables in a single query, you can do it with Ruby:
def home
@comments = Comment.all
@images = Image.all
@feed_items = (@comments + @images).sort_by(&:created_at)
end
Remember that using the all
method can be dangerous because you may have, potentially, tens of thousands of records. It's always a good idea to use a pagination system like will_paginate if nothing else.
You need to call sort and take
def home
@comments = Comment.all
@images = Image.all
@feed_items = (@comments+@images).sort{|x,y| y.created_by <=> x.created_by}
end
home.take(10)
精彩评论