bensheldon/activerecord-has_some_of_many

Is it possible to use `joins` with `has_one_of_many` associations?

aki77 opened this issue · 2 comments

Hello,
I was wondering if it is difficult to make associations defined with has_one_of_many usable with joins. It would be helpful in cases like the example below:

User.where(active: true).joins(:last_post).merge(Post.where(xx: true))

Is this feasible, or are there limitations that prevent this from being implemented?
Thank you for your time and assistance!

I did some explorational testing and the answer is: No, it's not possible to use joins, or joins-like methods, like includes(...).references(...), or where.association(...)/where.missing(...) with this library's associations.

That's probably ok, though not ideal.

The underlying intent of this Active Record extension is to offer a solution when an association specifically would benefit from applying an order and limit to the query. Neither of those are necessary when querying via a join... probably...most of the time? 🤷🏻

Tell me what use-cases I'm missing, but I imagine that one would still have has_many associations, in addition to this library's methods, and do the joins/etc. through those associatons:

class Post < ApplicationRecord
  has_many :comments
  has_many :published_comments, -> { where(published: true) }
  has_one_of_many :last_published_comment, -> { where(published: true).order(created_at: :desc) }
  has_some_of_many :last_two_published_comments { where(published: true).order(created_at: :desc) }
end


# All posts with published comments
Post.where.associated(:published_comments)
# Or
Post.includes(:comments).references(:comments).where(comments: { published: true }).distinct

Thank you for your response.

I asked because it would be great if we could, for example, achieve something like retrieving only the posts where the latest comment is published, similar to the sample code case:

Post.joins(:last_comment).merge(Comment.where(published: true))