Sky
Sky

Reputation: 4843

Order by association field using ActiveRecord

Is it possible to write an ActiveRecord query that sorts by an association field if the association exists, and otherwise sorts by an attribute on the object itself?

Example: I have a Discussion object which has_many :comments. I'd like to display a list of discussions sorted by discussion.latest_comment.created_at. However, some discussions may not have any comments, in which case I would like use their discussion.created_at attribute instead.

The catch is that I need the result to be an ActiveRecord::Relation (for performance reasons, and also because we are using Kaminari [which requires a Relation object]).

The only thing I could think of is to actually create a new field like discussion.latest_comment_at which would be initially populated by discussion.created_at and then updated every time a new comment is posted. However, this doesn't seem very straight-forward from a maintenance perspective (e.g. what happens when a comment gets deleted?).

Upvotes: 1

Views: 391

Answers (1)

Ryan Bigg
Ryan Bigg

Reputation: 107708

I don't know of a way to do this through SQL, so I cheated and I have my code set a last_post_at attribute whenever a topic is created.

That way, I can then sort the topics by last_post_at rather than having to query two tables at once.

I've seen other forum systems do it this way too, and it seems like what you're designing is exactly a forum-like system.

Upvotes: 1

Related Questions