1

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])
1
  • 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. Commented Nov 8, 2011 at 11:00

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.