You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

按关联数量排序对象:Rails中特定Stream专辑的对应排序实现问询

Answer

Got it, let's figure out how to adjust your existing query to sort genres based on album count only within a specific Stream.

Your original query works for all albums across all streams, but we need to narrow it down to just the albums belonging to a target Stream. Here's how to do it:

Step-by-Step Solution

Assuming you have a specific Stream instance (let's call it @target_stream), you can modify the query to:

Genre.left_joins(albums: :stream)
     .where(albums: { stream_id: @target_stream.id })
     .group(:id)
     .order('COUNT(albums.id) DESC')

Breakdown of the Query

  • left_joins(albums: :stream): This creates a nested left join between genres → albums → streams. Using left_joins ensures we keep all genres in the results, even if they have no albums in the target stream (their count will be 0).
  • where(albums: { stream_id: @target_stream.id }): This filters the joined albums to only those that belong to your specific stream.
  • group(:id): Groups the results by genre ID so we can count albums per genre.
  • order('COUNT(albums.id) DESC'): Sorts genres from most albums to least within the target stream.

Optional: Exclude Genres with No Albums in the Stream

If you don't want to include genres that have zero albums in the target stream, replace left_joins with joins instead:

Genre.joins(albums: :stream)
     .where(albums: { stream_id: @target_stream.id })
     .group(:id)
     .order('COUNT(albums.id) DESC')

Rails-Friendly Alternative (Avoid Raw SQL Strings)

For a more maintainable approach (especially if you're working across different databases), you can use Arel to build the count clause:

Genre.left_joins(albums: :stream)
     .where(albums: { stream_id: @target_stream.id })
     .group(:id)
     .order(Album.arel_table[:id].count.desc)

This way, Rails handles the SQL syntax for your database adapter automatically.

Example Outcome

If your target stream has more "Indie Rock" albums than any other genre, Indie Rock will be the first element in the returned array—just like your original query, but limited to the specific stream's albums.

内容的提问来源于stack exchange,提问作者StoyanovEZ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:19:45