Passing order-dependent array into ActiveRecord's find() method
Simple statement of the problem:
The ActiveRecord documentation shows that you can pass several values into
the object find() method, as follows:
Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
My issue is that the objects returned are insensitive to the order of the
values you pass in.
For instance, Person.find(1, 2, 6) returns exactly the same thing as
Person.find(6, 1, 2).
Is there any way to make this kind of search order sensitive?
It feels like there should be a way to pass in an array of id and get an
array of Person objects back in the same order...
Broader context, for those interested in reading on:
Really what I'm looking to do more generally, is find the "most viewed"
Person objects for a given time period.
Here's what I've got:
@most_viewed = View.where('created_at < ?', Time.now -
1.week).group(:person_id).order('count_person_id
desc').count('person_id').keys
This returns an (ordered!) array of id values for Person objects, in
descending order of number of Views each Person has received in the last
week.
My thinking was, if I could pass this array of ids into the Person.find
method, then I'm home free! But maybe there's another way entirely to do
it more easily. I'm open to all thoughts.
Thanks!
No comments:
Post a Comment