compsy
compsy

Reputation: 233

Rails Active Records using maximum and minimum simultaneously

Below both the query work fines

Event.joins(:visit).where(:page_id => 3).group(:visit_id).minimum('events.time')

Event.joins(:visit).where(:page_id => 3).group(:visit_id).maximum('events.time')

I want to do find the diff maximum('events.time') - minimum('events.time') and group by visit id

For this I am writing below query

Event.joins(:visit).where(:page_id => 3).group(:visit_id).(maximum('events.time') - minimum('events.time'))

I am getting error, (undefined method maximum for main:Object)

can anyone help me out for this active records query

Upvotes: 1

Views: 637

Answers (1)

NM Pennypacker
NM Pennypacker

Reputation: 6942

That's because you're trying to call maximum and minimum as though they were helper or instance methods. You have to call them on an instance of an ActiveRecord object. In your case I'm guessing that you have class Event < ActiveRecord::Base at the top of your model file.

Even if you change your code to use the ActiveRecord methods, you still have malformed Ruby code at (:visit_id).(maximum. So if the calculation performs and you get a date your code would look like this: Event.joins(:visit).where(:page_id => 3).group(:visit_id).(SomeTimeStamp), which will throw a different error.

You'll have to rework your query either way, but the important thing to note is that you can't call minimum or maximum as helper methods.

Upvotes: 1

Related Questions