2

ActiveRecord gives me a back a set of Users. I want to sort those users by a complex function that uses data not persisted in the User object.

Is there a way to use a scope when the data isn't persisted?

Is there a way to write a sort function as a class method, so I can make a call like:

sorted_users = User.first(20).sorted_my_way

1 Answer 1

3

i think it is not possible to do it this way.

it is possible to define class methods and scopes that can be called like User.first(20).sorted_my_way but those can only append stuff to the query you create. if you want to sort within ruby, i think that you need to wrap the whole stuff like:

class User
  self.sorted_my_way(limit)
    first(20).sort_by {...}
  end
end
User.sorted_my_way(20)

another thing that you could do would be to use a block style method:

class User
  self.sorted_my_way
    yield.sort_by {...}
  end
end
User.sorted_my_way { first(20) }
Sign up to request clarification or add additional context in comments.

1 Comment

I does appear to be impossible to do it with scopes. Your suggestions were good (and thanks for the primer on yield, though I didn't use it).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.