轨道不同表3合并多个查询 [英] rails 3 merge multiple queries from different tables
问题描述
我在我的控制器下面的查询。有没有办法,我可以将它们合并成一个什么办法?
@record_videos = RecordVideo.where(支持建议=?,真).limit(8)
@的音乐= Music.limit(13)
@ new_topics = Topic.limit(5).order(created_at降序)
没有,你不能将返回不同的类对象的多个查询。那么,你的可以的,从理论上讲,如果你写自己的查询的SQL,并使用了一些 UNION
S,但Rails的很可能不知道该怎么做的结果数据。我不能,随便,想用例,其中这将是一个好主意。
现在,您可以轻松地查询的结果结合起来,你的Ruby code事后 - 如果,例如,你想他们都整理在一起,你可以这样做:
@all_items = [@ record_videos.all,@ musics.all,@ new_topics.all] .flatten.sort_by {|事情| thing.created_at}
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")
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 UNION
s, 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}
这篇关于轨道不同表3合并多个查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!