Necesita ayuda para optimizar la consulta en ruby ​​on rails

I have some 30,000 records in my Raw_deals table and some raw_cities table has some 30 records and each deal is linked with some 5-8 cities.

Now i want to fetch any random deal within some specific cities.

List of those cities can be fetched like this:

@raw_cities = RawCity.where('disabled = ?', 0).map(&:id)

Now i need a deal. I wrote a query but its taking too much time.

@raw_deal = RawDeal.order("RAND()").find(:first,:joins=>[:raw_cities], :conditions=>["raw_cities.id IN (?)",@raw_cities])

preguntado el 08 de noviembre de 11 a las 10:11

you may try to random between randam date ranges, but you will always have trouble with performance if you want to apply a random algorithm in a table that is always growing. -

1 Respuestas

La order("RAND()") is probably what's slowing your query down, and since you're only looking for one single deal, you can use a combination of limit y offset to simulate a random order.

Intente algo como esto:

@raw_deal = RawDeal.offset(rand(RawDeal.count)).
                    joins(:raw_cities).
                    where(raw_cities: @raw_cities).
                    first

respondido 08 nov., 11:15

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.