Order two models with different attributes in one request

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 specific user and display her comments and posts in chronological order based on her update_at comments and last_edit_at attributes respectively.

I tried with the answer on 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?

+3


source to share


1 answer


you can 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 }

      

+4


source







All Articles