Rails / SQL Query finding most recent Event -


I am using Rail 4.2 and PostGrace SQL 9.4.

I have a basic user, reservation and incidents schema.

I would like to return the list of those users and the most recent incident, together at what time this date / time was in

I created a query that gives the user time and the most recent incident. However, I also need to return events.id .

My application does not allow the user to reserve two events with the same start time, although I appreciate it I know that SQL does not know anything about this and thinks that there can be many incidents in the result. Therefore, I am happy to query the event to return an appropriate event ID randomly in case of a fictitious 'tie' for events. Starsts_at

User.all.joins (reservation :: events) .select ('user. *, Max (events.starts_at)'). Where ('reservations.state =?', 'Present'). Where ('events.company_id =?', 1). The group ('User ID')

is the related SQL query: SELECT users. *, Max (events.starts_at) "user_id" "=" user "from" user "inner reservation" reservation "on" reservation "." ID "Inner Join" Event "On" Event "." Id "=" reservation "." Event.id

The reservation table is too large so the whole set should be loaded into the rail. And processing it via ruby ​​code is undesirable

My original model:

user
Has_many: reservation

Reservation
related_ to: user
related_ to: event

< Code> Event
related_to: company
is_im: reservation

Returns the data for the most recent incident Normal SQL looks like this:

  yourtables (select some fields, max (datefield) maxDateTime from table 1, where some fields by some fields) 1.someField = temp.somefield and temp1.dateTimeField = maxDateTime But whatever "things" should be identical with whatever "Wherever" things you have to do, all you have to do is create your app. You can put the query in a stored procedure that you call from your app. 


Comments

Popular posts from this blog

python - Overriding the save method in Django ModelForm -

html - CSS autoheight, but fit content to height of div -

qt - How to prevent QAudioInput from automatically boosting the master volume to 100%? -