gpt4 book ai didi

ruby-on-rails - 通过关联从具有多个关联中获取第一个关联

转载 作者:数据小太阳 更新时间:2023-10-29 06:46:12 25 4
gpt4 key购买 nike

我正在尝试将每个播放列表的第一首歌曲加入到播放列表数组中,但我很难找到有效的解决方案。

我有以下模型:

class Playlist < ActiveRecord::Base
belongs_to :user
has_many :playlist_songs
has_many :songs, :through => :playlist_songs
end

class PlaylistSong < ActiveRecord::Base
belongs_to :playlist
belongs_to :song
end

class Song < ActiveRecord::Base
has_many :playlist_songs
has_many :playlists, :through => :playlist_songs
end

我想得到这个:

playlist_name  |  song_name
----------------------------
chill | baby
fun | bffs

我很难找到一种有效的方法来通过连接来做到这一点。

更新 ****

Shane Andrade 引导我朝着正确的方向前进,但我仍然无法得到我想要的。

这是我所能得到的:

playlists = Playlist.where('id in (1,2,3)')

playlists.joins(:playlist_songs)
.group('playlists.id')
.select('MIN(songs.id) as song_id, playlists.name as playlist_name')

这给了我:

playlist_name  |  song_id
---------------------------
chill | 1

这很接近,但我需要第一首歌(根据 id)的名字。

最佳答案

假设你在 Postgresql 上

Playlist.
select("DISTINCT ON(playlists.id) playlists.id,
songs.id song_id,
playlists.name,
songs.name first_song_name").
joins(:songs).
order("id, song_id").
map do |pl|
[pl.id, pl.name, pl.first_song_name]
end

关于ruby-on-rails - 通过关联从具有多个关联中获取第一个关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15301086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com