2016-09-29 70 views
0

我的應用程序顯示事件建議給用戶。已經想出一個問題是,有時有多個事件,不同的日期,在一個系列,如:活動記錄:顯示的第一個對象的一系列對象(優化)

  • 斯坦利劇院提出「富酒吧之夜1
  • 斯坦利劇院提出」富酒吧之夜2
  • 斯坦利劇院提出「富酒吧之夜3

我想這樣做是顯示用戶只有一個在最近的將來開始日期的一系列事件。

我可以寫一個檢查的方法,如果一個事件是在一個系列的第一:

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 
在我的活動指數

然後,我可以寫這樣的:

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

但這似乎就像我在渲染所有事件時會徵稅一樣。我如何使用Active Record Scopes優化此查詢?

+0

什麼是我不能在這裏把握的問題 –

+0

'next'當你將有一個永遠'first_in_series'(順便說一句,方法應該沒有'?'),因爲它不是布爾返回 –

+0

@AndreyDeineko做了一些修改。 'first_in_series'中並不總是有一個。當self.siblings.where(:date => Date.today..self.date).first.present?返回false ...這意味着該事件已擁有自己的日期 –

回答

2

我覺得範圍可以爲您解決:

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

然後,如果我沒有記錯,下面應該工作:

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

嘿@AndreyDeineko - 謝謝你的回答。問題是我沒有「兄弟姐妹」模式。我只能確定事件是否通過自定義方法的兄弟姐妹比較標題和地點 –

+0

對不起 - 我的「兄弟姐妹」令人困惑的措辭 –

+0

@JacksonCunningham顯示兄妹方法呢:) –

相關問題