← Back to Upcase

Sorting array of multiple classes of objects by dynamic attribute

(Tamas Erdos) #1

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

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:


def sort_column
Question.column_names.include?(params[:sort]) ? params[:sort] : "updated_at"

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 Erdos) #2

Solved this by using the send method:

col = sort_column
@items.sort! {|b,a|
if sort_direction == "desc"
a.send(col.to_sym) <=> b.send(col.to_sym)
b.send(col.to_sym) <=> a.send(col.to_sym)

(Derek Prior) #3

Why is sort_column private if you intend to use it outside of the class that defines it?

(Tamas Erdos) #4

@derekprior Right now it’s defined in the controller, but you’re right I should move it to the applicationcontroller because I make use of it in other controllers as well and it’s not very DRY. Thanks