A
A
Andrey2017-11-01 15:02:14
Ruby on Rails
Andrey, 2017-11-01 15:02:14

How to convert array to relation?

I know that these are the wrong actions initially, but still, in my case I see no other way out.
There are goods - model Items (table items).
The price for them is built dynamically - the PriceItems model (there is no table).
I need to sort goods by price, I do

@products.map do |product|
        price = @prices["#{product.make_name}-#{product.oem}"] #здесь получаю цену конкретного товара
        if price.present?
          [price.cost, product]
        end
      end

It turns out this array:

I do next
j = s.sort_by {|h| h[0]} # сортирую по цене
w = j.each {|el| el.delete_at(0)} # удаляю цену и получаю [[#<Product id: 3], [#<Product id: 4], [#<Product id: 2], [#<Product id: 1] ]
@sort_products = w.flatten #Получаю массив с объектами [#<Product id: 3, #<Product id: 4, #<Product id: 2, #<Product id: 1]

In general, I get an array of objects, how can I convert it to an array of objects ActiveRecord::Relation?
Actually I do but returns this AR:Relation sorted by id (i.e. returned to original state) Items.where(id: @sort_products.map(&:id))

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
A
Andrey Demidenko, 2017-11-01
@Dem1

You cannot convert array to ActiveRecord::Relation. Since Relation is a build for a SQL query.

R
Robert, 2017-11-15
@Jowan

Building the price dynamically every time is a bad idea, you need to store such things in the database.

Z
Zaporozhchenko Oleg, 2017-11-01
@c3gdlk

Sorting is spoiled to you by the basis, means and the decision needs to be looked for at the level of a database. For postgres, choose any here - https://stackoverflow.com/questions/866465/order-b... The
query will have to be built dynamically, but this is not particularly difficult.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question