问题
i have the following queries in my controller. Is there any way that i can merge them into one?
@record_videos = RecordVideo.where("recommand = ?",true).limit(8)
@musics=Music.limit(13)
@new_topics=Topic.limit(5).order("created_at desc")
回答1:
No, you cannot combine multiple queries that return different classes of object. Well, you could, theoretically, if you wrote your own query SQL and used a few UNIONs, but Rails would likely have no idea what to do with the resulting data. I can't, offhand, think of a use-case where this would be a good idea.
Now, you can easily combine the results of the queries after the fact in your Ruby code - if, for instance, you wanted to sort them all together, you could do this:
@all_items = [@record_videos.all, @musics.all, @new_topics.all].flatten.sort_by{ |thing| thing.created_at}
来源:https://stackoverflow.com/questions/17994709/rails-3-merge-multiple-queries-from-different-tables