user419017
user419017

Reputation:

ActiveRecord merge datasets of same model?

I have a model, lets say Ad, which I plan to fetch 2 datasets from, then merge them into 1. Is this possible:

ads = Ad.where(etc).limit(5)

if ads.length < 5
  merge = Ad.where(etc).limit(remainder)

// merge both here

Upvotes: 1

Views: 197

Answers (1)

Chamnap
Chamnap

Reputation: 4766

ActiveRecord allows you to do chaining. Try this out, it will execute only one query.

ads = Ad.where(etc).limit(5)
ads = ads.where(etc).limit(remainder)

But in your case, you call the length method so it will execute two queries. However, you can still do chaining. User count method is better than length method because count will send a COUNT(*) to your database (faster). length will load all records based on the where conditions and do a count on array (slower).

ads = Ad.where(etc).limit(5)
if ads.count < 5
  ads = ads.where(etc).limit(remainder)
end

Upvotes: 3

Related Questions