3
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?

Community
  • 1
  • 1
Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232

1 Answers1

5

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 }
SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53