I have a very janky query that I'm trying to optimize. I want to return an activerecord association of user records based on some membership packet logic.
ids = User.joins(:memberships).includes(:memberships).select do |user|
if user.memberships.count <= 1
user.membership_packet_sent_at.blank?
else
user.membership_packet_sent_at.blank? && user.current_membership.created_more_than_30_days_ago?
end
end.uniq.map(&:id)
User.where(id: ids)
The issue I am running into above is that I have to make two queries since I don't know how to use select to return an active record association instead of an array.
- How do I return an activerecord association from select?
- Is there a better way for me to organize my logic inside the select block?
Edit:
After some refactoring, I was able to move some of the select logic into methods:
```
ids = User.joins(:memberships)
.where(membership_packet_sent_at: nil)
.select(&:current_membership_packet_expired?)
.uniq
.map(&:id)
User.where(id: ids)
```
Still running into the issue of how to return an activerecord association instead