Очевидный способ для нахождения ActiveRecord возражает идентификатором в указанном порядке

Если вы хотите, чтобы элементы были смежными, вы можете использовать старую добрую 2-кратную динамическую конструкцию массива:

// allocate a dynamic array
NonMoveable *mv = std::allocator<NonMoveable>().allocate(args.size());

// use inplace new to construct the NonMoveable elements
for (unsigned int i = 0; i < args.size(); i++) {
    new(mv + i) NonMoveable(args[i], additional_arg);
}

...  // use the dynamic array

// Explicitely delete the elements
for (unsigned int i = 0; i < args.size(); i++) {
    mv[i].~NonMoveable();
}

// and de-allocate
std::allocator<NonMoveable>().deallocate(mv, args.size());

Это скорее C-ish, но удовлетворяет смежным требованиям. Конечно, это должно быть заключено в специальный контейнер, чтобы обеспечить автоматическое уничтожение и удаление при уничтожении контейнера.

26
задан mu is too short 9 June 2014 в 04:34
поделиться

3 ответа

It's not that MySQL and other DBs sort things on their own, it's that they don't sort them. When you call Model.find([5, 2, 3]), the SQL generated is something like:

SELECT * FROM models WHERE models.id IN (5, 2, 3)

This doesn't specify an order, just the set of records you want returned. It turns out that generally MySQL will return the database rows in 'id' order, but there's no guarantee of this.

The only way to get the database to return records in a guaranteed order is to add an order clause. If your records will always be returned in a particular order, then you can add a sort column to the db and do Model.find([5, 2, 3], :order => 'sort_column'). If this isn't the case, you'll have to do the sorting in code:

ids = [5, 2, 3]
records = Model.find(ids)
sorted_records = ids.collect {|id| records.detect {|x| x.id == id}} 
22
ответ дан 28 November 2019 в 06:58
поделиться

Очевидно, MySQL и другие системы управления БД сортируют вещи самостоятельно. Я думаю, что вы можете обойти это, выполнив:

ids = [5,2,3]
@things = Object.find( ids, :order => "field(id,#{ids.join(',')})" )
6
ответ дан 28 November 2019 в 06:58
поделиться
@things = [5,2,3].map{|id| Object.find(id)}

Это, вероятно, самый простой способ, при условии, что у вас не так много объектов для поиска, поскольку для каждого идентификатора требуется поездка в базу данных.

-1
ответ дан 28 November 2019 в 06:58
поделиться
Другие вопросы по тегам:

Похожие вопросы: