gpt4 book ai didi

ruby-on-rails - rails : Method for joining if a user has liked a set of songs

转载 作者:行者123 更新时间:2023-12-04 06:09:16 26 4
gpt4 key购买 nike

我有以下型号:

  • 用户
  • 播放列表
  • SongLike
  • ...

  • 当我查询播放列表的所有歌曲时,我会返回一组歌曲对象。找出用户“喜欢”哪些歌曲的最有效方法是什么?喜欢存储在 SongLike 模型中:
    class SongLike < ActiveRecord::Base
    belongs_to :user
    belongs_to :song, :counter_cache => "likes_count"
    end

    ...这是歌曲模型:
    class Song < ActiveRecord::Base
    has_and_belongs_to_many :playlists
    has_many :featured_songs
    has_many :song_likes
    has_many :users, :through => :song_likes
    ...
    end

    最佳答案

    利用您的 Song_likes 关联以及内存中的歌曲,而不是多次查询数据库:

    # user.rb
    def songs_liked_from(subset)
    like_ids = self.song_likes.where(:song_id => subset.map(&:id)).select(:song_id).map(&:song_id)
    subset.select{|s| liked_ids.include?(s.id) }
    end

    关于ruby-on-rails - rails : Method for joining if a user has liked a set of songs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7971247/

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