如何获取一组属性与另一组属性的关联?
How to get a group of attributes associated with another group of attributes?
这应该很简单,但我在寻找答案时遇到了很多奇怪的麻烦。我只想要一组通过外键关联到另一组记录的记录。例如,如果我通过 Song.artist_id 有歌曲 belongs_to 艺术家,并且通过 Artist.where(mustache: true)
有一组艺术家,我想要一个查询 returns 所有属于所有的歌曲那些艺术家。所以像:
@songs = Artist.where(mustache: true).songs
但这确实有效。
Song.where(artist_id: Artist.where(mustache: true).select(:id))
或
song.joins(:artist).where(artists: {mustache: true})
这应该很简单,但我在寻找答案时遇到了很多奇怪的麻烦。我只想要一组通过外键关联到另一组记录的记录。例如,如果我通过 Song.artist_id 有歌曲 belongs_to 艺术家,并且通过 Artist.where(mustache: true)
有一组艺术家,我想要一个查询 returns 所有属于所有的歌曲那些艺术家。所以像:
@songs = Artist.where(mustache: true).songs
但这确实有效。
Song.where(artist_id: Artist.where(mustache: true).select(:id))
或
song.joins(:artist).where(artists: {mustache: true})