I've got result from below query:
query
class SyncResult
def self.query(products)
Imports::Product
.order(:last_sync_at)
.pluck(:id, :name, :code, :sync_result, :last_sync_at)
.map do |id, name, code, result, last_sync_at|
{
id: id,
name: name,
code: code,
result: result,
last_sync_at: last_sync_at
}
end
end
end
query result
=> [{:id=>"611ea9a7392ab50013cf4713", :name=>"2-Tone Hoodie", :code=>"SS22CH013", :result=>nil, :last_sync_at=>nil},
{:id=>"60ec84062f25d400150b351c", :name=>"5-Pocket Denim", :code=>"SS22WP014", :result=>nil, :last_sync_at=>nil},
{:id=>"61966dc83e81dd001731ccd7", :name=>"Zip Shirt Jacket", :code=>"FW22WT001", :result=>nil, :last_sync_at=>nil},
{:id=>"61d5cab6b41408001b0e9376", :name=>"Yankees Satin Varsity Jacket", :code=>"FW22WJ021", :result=>nil, :last_sync_at=>nil}]
products = ['SS22CH013', 'FW22WJ021']
Now I want to get only these array hash element which incudes code from products
array.
End result should be:
=> [{:id=>"611ea9a7392ab50013cf4713", :name=>"2-Tone Hoodie", :code=>"SS22CH013", :result=>nil, :last_sync_at=>nil},
{:id=>"61d5cab6b41408001b0e9376", :name=>"Yankees Satin Varsity Jacket", :code=>"FW22WJ021", :result=>nil, :last_sync_at=>nil}]
CodePudding user response:
You can achieve the expected result in following ways.
- Updating query to fetch Products for given codes
products = ['SS22CH013', 'FW22WJ021'] Imports::Product .where(code: products) .order(:last_sync_at) .pluck(:id, :name, :code, :sync_result, :last_sync_at) .map do |id, name, code, result, last_sync_at| { id: id, name: name, code: code, result: result, last_sync_at: last_sync_at }
- Updating query to fetch Products for given codes(without pluck)
products = ['SS22CH013', 'FW22WJ021'] Imports::Product .where(code: products) .order(:last_sync_at) .select(:id, :name, :code, :sync_result, :last_sync_at) .map(&:attributes)
- using
select
on query resultquery_result = [{:id=>"611ea9a7392ab50013cf4713", :name=>"2-Tone Hoodie", :code=>"SS22CH013", :result=>nil, :last_sync_at=>nil}, {:id=>"60ec84062f25d400150b351c", :name=>"5-Pocket Denim", :code=>"SS22WP014", :result=>nil, :last_sync_at=>nil}, {:id=>"61966dc83e81dd001731ccd7", :name=>"Zip Shirt Jacket", :code=>"FW22WT001", :result=>nil, :last_sync_at=>nil}, {:id=>"61d5cab6b41408001b0e9376", :name=>"Yankees Satin Varsity Jacket", :code=>"FW22WJ021", :result=>nil, :last_sync_at=>nil}] products = ['SS22CH013', 'FW22WJ021'] query_result.select{ |product| products.include?(product[:code]) }