scott2619
(Scott Hollinshead)
March 30, 2015, 3:28pm
1
Is there a way of ordering by an array?
something like?
arr = [10,14,1,3]
where(id: arr).order(arr)
I know the above doesn’t work, it’s how I would like it to work.
At the moment without the order part, it is finding all the id’s in the array but listing them in ascending order.
Thanks
scott2619
(Scott Hollinshead)
March 30, 2015, 3:37pm
2
I have just found that I can do this, but it seems a little slow, any other suggestions?
arr = [10,14,1,3]
where(id: arr).order("field(id, #{arr.join(',')})")
Here is a link to what field() does
Is there a significance to the array? what does that collection represent?
scott2619
(Scott Hollinshead)
March 31, 2015, 7:20am
4
@pedromoreira Yes it’s a list of catalogue id’s that the customer is allowed to see, however the first one is the most important, it’s the one that gets set as the default, but because the where
clause is ordering them in ASC
in this case it would pick up 1 as the first.
andyw8
(Andy Waite)
March 31, 2015, 9:30pm
5
How about adding an is_default
field to the Catalogue model? Then you can order the result using a query something like order(is_default: :desc, name: asc)
so that the default always appears first.
scott2619
(Scott Hollinshead)
April 1, 2015, 7:46am
6
Hi Andy,
I can’t really do that, as the order of the catalogues is important .
Thanks,
andyw8
(Andy Waite)
April 1, 2015, 7:50am
7
Is that information encoded in the database, e.g. a display_order
field?
scott2619
(Scott Hollinshead)
April 1, 2015, 8:49am
8
Yes it’s in a database as catalog_list
andyw8
(Andy Waite)
April 1, 2015, 6:38pm
9
How is it stored? A plain string? A postgres array?
scott2619
(Scott Hollinshead)
April 2, 2015, 7:18am
10
It’s a string in MySQL DB
andyw8
(Andy Waite)
April 2, 2015, 7:59am
11
You could try do the sorting in Ruby rather than SQL. I’ve no idea if this would be faster than the MySQL approach using fields()
.
For example:
ordered_catalogue_ids = user.catalog_list.split(",").map(&:to_i)
ordered_catalogues = catalogues.where(id: catalogue_ids).sort_by do |catalog_id|
ordered_catalogue_ids.index(catalog_id)
end
scott2619
(Scott Hollinshead)
April 2, 2015, 8:11am
12
Thanks Andy I will give that a go .
where is ordering
coming from?
andyw8
(Andy Waite)
April 2, 2015, 4:04pm
13
Sorry, I’ve corrected my post.
jessieay
(Jessie Young)
April 6, 2015, 11:41pm
14
lenart
(Lenart Rudel)
April 21, 2015, 1:46pm
15
Just came across a blog post by Justin Weiss that solves just this.
scott2619
(Scott Hollinshead)
April 21, 2015, 2:44pm
16
@lenart thanks It looks like using field
is the right way to go then.