rolkos
rolkos

Reputation: 342

Rails 4 - order by related models created_at - activity

In my rails app I have few related models for example:

Event

has_many :comments
has_many :attendents
has_many :requests

What I need is to order by 'created_at' but not only main model (Event) but also related models, so I will display on top of the list event with most recent activity i.e.: comments, attendents, requests

So if Event date is newer than any comment, request or attendent date this event will be on top. But if there is an event with newer comment this one will be on top etc.

How should I implement such ordering?

EDIT db is mysql

Thanks

Upvotes: 1

Views: 108

Answers (3)

David Aldridge
David Aldridge

Reputation: 52336

I would place a column on the event for last_activity, and maintain it by touching from the associated models.

The alternative is to order by using a join or subquery against the other tables, which is going to require a database query that will be much less efficient than simply ordering by last_activity descending.

Upvotes: 2

lx00st
lx00st

Reputation: 1596

Event
  .select("events.*")
  .joins("LEFT OUTER JOIN comments ON comments.event_id = events.id")
  .joins("LEFT OUTER JOIN attendents ON attendents.event_id = events.id" )
  .joins("LEFT OUTER JOIN requests ON requests.event_id = events.id")
  .group("events.id")
  .order("GREATEST(events.created_at, 
          MAX(comments.created_at),
          MAX(attendents.created_at),
          MAX(requests.created_at)) DESC")

Upvotes: 1

HermannHH
HermannHH

Reputation: 1772

If I understand your question correctly, something like this

Firstly add this to your Models in question:

default_scope order('created_at DESC')

Then I would do some grouping:

@comments = Comment.all
@comments_group = @comments.group_by { |c| c.event}

And in your view you'll be able to loop through each block:

@comments_group.each do |event, comment|
  - event.name
  comment.each do|c|
    - c.body

I did not test this but it should give you an idea.

Upvotes: 0

Related Questions