Fellow Stranger
Fellow Stranger

Reputation: 34013

Order two models by different attributes in one query

class Comment < ActiveRecord::Base
  #  updated_at :datetime
  belongs_to :user
end

class Post < ActiveRecord::Base
  #  last_edit_at :datetime
  belongs_to :user
end

I want to query a certain user and display her comments and posts chronologically, based on her comments updated_at attribute and posts last_edit_at attribute respectively.

I've tried with an answer from a similar question, but there the attributes are the same:

combined_sorted = (User.comments + User.likes).sort{|a,b| a.created_at <=> b.created_at }

How could I accomplish the above but with unique attributes?

Upvotes: 3

Views: 775

Answers (1)

SteveTurczyn
SteveTurczyn

Reputation: 36860

you could create some alias attributes...

class Comment < ActiveRecord::Base
  #  updated_at :datetime
  alias_attribute :sort_date, :updated_at
  belongs_to :user
end

class Post < ActiveRecord::Base
  #  last_edit_at :datetime
  alias_attribute :sort_date, :last_edit_at
  belongs_to :user
end

user = User.first # replace with method to retrieve desired user
combined_sorted = (user.comments + user.likes).sort{|a,b| a.sort_date <=> b.sort_date }

Upvotes: 5

Related Questions