Reputation: 43959
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])
Upvotes: 1
Views: 110
Reputation: 11987
The 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
and offset
to simulate a random order.
Try something like this:
@raw_deal = RawDeal.offset(rand(RawDeal.count)).
joins(:raw_cities).
where(raw_cities: @raw_cities).
first
Upvotes: 3