おそらくこれはRailsである必要があります。あなたは、異なる店舗のすべてを別々の列にまとめたいと思うでしょう。次に、ネストされたループを使用して、すべての配列が空になるまで最初のレコードをポップします。私は、データベースへのクエリが1つまたは2つだけで、Railsでこのようなことが起こると思います。このような
何か:
# Initialize product grouping hash
grouped_products = {}
# Produces hash of product arrays.
# Each array contains all of the products for a shop.
Products.all.order(:shop_id, :name).each do | product |
grouped_products[product.shop_id] = [] if grouped_products[product.shop_id].nil?
grouped_products[product.shop_id] << product
end
# Now we turn all of our grouped arrays into enumerators
grouped_products.each_key do | key |
grouped_products[key] = grouped_products[key].each
end
alternating_products = []
# Here we build the alternating products array
loop do
# Get the next product from the top of each grouped array
grouped_products.each_key do |key|
# Add the next product from the current array to the alternating array
begin
alternating_products << grouped_products[key].next
# If at the end of the current array, remove it from the hash
rescue StopIteration
grouped_products.except! key
end
end
# Stop looping when all arrays are empty and removed from hash
break if grouped_products.empty?
end
alternating_products
私は上記のコードをテストしていないので、いくつかの微調整が必要な場合があります。
これは、データセット全体を2回ループする必要があります。
これは順序付き配列を返すので、かなり簡単に改ページできます。たとえば、最初の10レコードを取得するには、alternating_products[0..9]
を使用します。 10レコードの2番目のセットを取得するにはalternating_products[10..19]
などを使用します。
あなたは3つずつ交替したいと思っていますか?また、これは宿題の問題ですか? –
こんにちは@TomAranda、回答ありがとう 私が取り組んでいるプロジェクトです。 店舗数は3に限定されず、5,10,15以上で変更できます。 私はランダムな順序付けを使用し、検索が行われた後にハッシュを調整することができますが、それでも問題になる可能性があります。ショップ1の製品のみになると間違ったリストになります。 このような理由から、私は結果が既にクエリによって変更された状態にする方法を探しています –
私はあなたが複数のステップでこれを行う必要があると思います。 1つのクエリが機能するかどうかはわかりません。私はそれについて考える必要があります。 –