我有以下模型,并希望获得特定用户尚未点赞的所有可用帖子。
帖子模型:
class Post < ActiveRecord::Base
has_many :likes
has_many :users, through: :likes
scope :available, -> { where available: true }
end
喜欢模特:
class Like < ActiveRecord::Base
belongs_to :post
belongs_to :user
end
用户模型:
class User < ActiveRecord::Base
has_many :likes
has_many :posts, through: :likes
end
我想到了这个 ActiveRecord 查询:
Post.available - Post.available.joins(:likes).where('likes.user_id = ?', user.id)
是否有优化的方法来实现这一点?甚至可能是等效的 SQL 查询?
最佳答案
这可以通过以下方式实现:
Post.available.where("id not in (select post_id from likes where user_id = ?)", user.id)
关于sql - 优化 ActiveRecord 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33915928/