I have the following model in Ruby
class Entity < ActiveRecord::Base
validates :account_type, presence: true
validates :account_id, presence: true
end
and I have an array of hashes called accounts something like:
[{'account_id':44, 'account_type':'user'},..,{'account_id':44, 'account_type':'other'}, {'account_id':88,
'account_type':'another'}]
So I want a way to obtain all the entities that match with the elements of the accounts array (account_id and account_type both at same time).
I tried using this code:
entities = []
accounts.each do |account|
entities << Entity.where(account_id: ActiveSupport::HashWithIndifferentAccess.new(account)['account_id'])
.where(account_type: ActiveSupport::HashWithIndifferentAccess.new(account)['account_type'])
end
But there is a way to do it more efficient ??
HashWithIndifferentAccess, if you are only accessing by string? The twowhereclauses look like they could be combined intowhere(account_id: account['account_id'], account_type: account['account_type]), or possiblywhere(account)if you trust the attributes. You could also useEntity.select('id, name').where()to reduce the number of fields pulled if you don't need them.