【发布时间】:2019-03-19 21:36:02
【问题描述】:
我在 Ruby 中有以下模型
class Entity < ActiveRecord::Base
validates :account_type, presence: true
validates :account_id, presence: true
end
我有一个称为帐户的哈希数组,例如:
[{'account_id':44, 'account_type':'user'},..,{'account_id':44, 'account_type':'other'}, {'account_id':88,
'account_type':'another'}]
所以我想要一种方法来获取与帐户数组的元素匹配的所有实体(account_id 和 account_type 两者同时)。
我尝试使用此代码:
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
但是有一种方法可以提高效率??
【问题讨论】:
-
既然要一条记录同时匹配两个属性,那我想不出更好的办法了。但是,可能有更好的方法来完成您尝试做的任何事情。也许您遵循的逻辑存在问题,导致您需要该查询,而不是查询本身。
-
如果只通过字符串访问,是否需要转换为
HashWithIndifferentAccess?两个where子句看起来可以组合成where(account_id: account['account_id'], account_type: account['account_type]),或者如果您信任这些属性,也可以组合成where(account)。如果您不需要它们,也可以使用Entity.select('id, name').where()来减少提取的字段数量。
标签: ruby-on-rails activerecord rails-activerecord