I’m trying to sort 3 similar classes of objects that share some attributes. My array is (not very elegantly) defined like this:
@user = User.find(params[:id])
itemss = Question.where(user_id: @user.id)
items2 = Answer.where(user_id: @user.id)
items3 = Comment.where(user_id: @user.id)
itemss.push items2
itemss.push items3
itemss=itemss.flatten
I would now like to sort this array by a common attribute. Most efficient one seems to be sort_by, so now my code reads:
itemss.sort_by!(&:sort_column)
private
def sort_column
Question.column_names.include?(params[:sort]) ? params[:sort] : “updated_at”
end
This fails, because none of my models have the actual attribute “sort_column”. Is there a way to reference this dynamically? Or call something like: itemss.sort! {|a,b| a.sort_column <=> b.sort_column}
Thank you,
Tamas