使用哈希数组在活动记录中查询

时间:2019-03-19 21:36:03

标签: ruby-on-rails activerecord rails-activerecord

我在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'}]

所以我想要一种方法来获取与accounts数组的元素(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

但是有一种方法可以使它更有效?

3 个答案:

答案 0 :(得分:2)

为此:

[{'account_id':44, 'account_type':'user'}, {'account_id':44, 'account_type':'other'}, ... ]

您想要的SQL是:

select ...
where account_id = 44 and account_type = 'user'
   or account_id = 44 and account_type = 'other'
   or ...

请注意,SQL的运算符优先级使其与以下各项相同:

select ...
where (account_id = 44 and account_type = 'user')
   or (account_id = 44 and account_type = 'other')
   or ...

您可以使用ActiveRecord建立类似的查询,但是由于#or的工作方式,这有点麻烦:

accounts = your_array_of_hashes
entities = accounts.inject(Entity.none) { |memo, h| memo.or(Entity.where(h)) }

答案 1 :(得分:1)

如果您使用滑轨5,则可以尝试or。像这样

entities = Entity.none
items.each do |item|
  entities = entities.or(Entity.where(item))
end

这只是一个SQL查询,但是如果数组很大,我不知道它是如何工作的。

答案 2 :(得分:0)

如果我遇到您的问题,这应该可以解决:

entities = accounts.map { |acc| Entity.where(account_id: acc['account_id'], account_type: acc['account_type']) }

让我解释发生了什么事

  • 首先,方法map返回一个数组,将所有与数据库中的内容匹配的条目
  • map就像each一样通过Accounts数组进行插入,这意味着它将把帐户中的数据带到where查询中
  • comma条件之间的where也可以进行比较,除非您正在做or,在我想可以使用以下语法的情况下:where('account_id = :id or account_type = :type', id: acc['account_id'], type: acc['account_type'])
相关问题