使用场景如ruby china中的我的收藏功能:
Topic.find(@user.favorite_topic_ids)
或者
Topic.where("id in (@user.favorite_topic_ids)")
请问如何才能让返回结果也能按照指定的favorite_topic_ids的顺序进行排序呢?
SELECT * FROM tablename WHERE id IN (1,10,8,5) ORDER BY FIND_IN_SET(id, '1,10,8,5')
Topic.find(@user.favorite_topic_ids).sort_by { |topic| @user.favorite_topic_ids.index(topic.id) }
你抽出来以后内存排序就是了,
首先开启 idendity_map
@topics = Topic.where("id in (@user.favorite_topic_ids)")
@user.favorite_topic_ids.each {|id| (@topics_ordered ||=[]) << Topic.find(id)}
由于开启了 idendity_map,不会有额外的查询
ids = @user.favorite_topic_ids.join(",") Topic.where("id in (?)",ids).order("field(id #{ids})") 不知道这样可以吗