Jackson Cunningham
Jackson Cunningham

Reputation: 5073

Active Record: Showing the first object in a series of objects (optimization)

My app shows event suggestions to users. One issue that has come up is that sometimes there are multiple events, with different dates, in a series, e.g:

What I would like to do is show the user only one event in a series with the nearest future start date.

I could write a method that checks if an event is the first in a series:

def first_in_series?
  ## return true unless self.siblings.count > 0 && 
    self.siblings.where(:date => Date.today..self.date).first.present?
end

def siblings
  ## some method to get events based on the similarity of their titles and attributes
end

Then in my events index, I could write something like:

<% future_events.all.each do |e| %>
  <% next unless event.first_in_series? %>
  <%= event.title %>
<% end %>

But this seems like it would be taxing when I'm rendering all my events. How can I optimize this query using Active Record Scopes?

Upvotes: 0

Views: 17

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52357

I think scope might solve it for you:

class Event
  has_one :first_sibling, lambda {
    joins(:siblings).where('siblings.date >= ?', Date.today).first
  }
end

Then, if I'm not mistaken, the following should work:

<%- future_events.joins(:first_sibling).each do |event| %>
  <%= event.title %>
<% end %>

Upvotes: 2

Related Questions