0

i have a custom method on my model and i want to use it in a where condition, i already accomplish this for sorting with custom methods, but can't find a way for search with custom conditions.

Now i have this, in my model

attr_accessible :end, :start
def time_left
  self.end.to_i - Time.now.utc.to_i - Time.now.utc_offset
end
def time_left_to_start
  self.start.to_i - Time.now.utc.to_i - Time.now.utc_offset
end
def status
  if self.time_left_to_start > 0 
    1 #proximamente
  elsif self.time_left_to_start < 0 and self.time_left > 0
    2 #funcionando
  else
    3 #finalizado
  end
end

and for my controller

def index
  @next_events = Event.all.sort_by(&:time_left).reverse!.reject { |e| e.status != 1 }.take(5)
end

i know i can write the entire condition on the where method, but my idea is don't repeat my self and avoid to loop for all the events to remove each one where the status isn't 1, i just need the last 5 each time and looks to me really bad idea ask to the db for all the records each time. Thanks in advance, regards!

1
  • It's impossible to do such thing. I guess you need to write a piece of SQL code. Commented Mar 19, 2014 at 12:36

1 Answer 1

1

After refactoring my code i came across with this

  def time_left
    (self.end - Time.now).to_i
  end
  def time_left_to_start
    (self.start - Time.now).to_i
  end

  def status
    if self.start  < Time.now and self.end > Time.now
      1 #En curso
    elsif self.start  > Time.now
      2 #Proximamente
    else
      3 #Finalizado
    end      
  end

  def self.status(status)
    if status == 1 #eventos en curso
      where("(events.start < ?) AND (events.end > ?)", Time.now, Time.now)
    elsif status == 2 #proximos eventos
      where("events.start > ?", Time.now)
    elsif status == 3 #eventos finalizados
      where("events.end < ?", Time.now)
    elsif status == 4 #eventos proximos y en curso
      where("events.end > ?", Time.now)
    end
  end

and making queries like this

  @next_events = Event.status(2).order('events.start DESC').reject { |e| e.time_left_to_start > 12.hour }.take(18)

Thanks for your time, regards!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.