rails 3 merge multiple queries from different tables

时间秒杀一切 提交于 2019-12-11 15:48:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!