Search code examples
sqlruby-on-railspostgresqlactiverecordquery-optimization

Optimizing an ActiveRecord query


I have the following models and want to get all the available posts that an specific user has not put a like on them.

Post Model:

class Post < ActiveRecord::Base
  has_many :likes
  has_many :users, through: :likes

  scope :available, -> { where available: true }
end

Like Model:

class Like < ActiveRecord::Base
  belongs_to :post
  belongs_to :user
end

User Model:

class User < ActiveRecord::Base
  has_many :likes
  has_many :posts, through: :likes
end

I came up with this ActiveRecord query:

Post.available - Post.available.joins(:likes).where('likes.user_id = ?', user.id)

Is there an optimized way to achieve this? Maybe even an equivalent SQL query?


Solution

  • This can be achieved with:

    Post.available.where("id not in (select post_id from likes where user_id = ?)", user.id)