我正在使用 Rails 5。
我必须处理一个非常复杂的查询,其中包含多个相同的 where 子句:
::AllocatedBudget.joins(:account_code, :budget, account_code: [:place],
budget: [:fiscal_year, :budget_state])
.where(immeuble: { id: place.id })
.where(situation_budget: { codesituation: ['A', 'V']})
.where(plan_comptable: { supprime: 'false' })
.where(budget: { supprime: 'false'})
.where(situation_budget: { supprime: 'false' })
.where(budget_previsionnel: { supprime: 'false' })
.where(exercice_comptable: { supprime: 'false' })
首先,您必须知道我的模型连接到名称难看的旧数据库。我注意到 ActiveRecord 需要自定义名称而不是模型名称来执行查询。我不知道为什么,但它只能以这种方式工作......如果有人可以解释那会很好;)
我真正的问题是:我可以用更好的方式编写它吗?有这么多次相同的 where 子句 "supprime = 'false' "。
非常感谢! :)
最佳答案
我会把问题分成两步
- 使用纯 ruby 代码创建所有条件的散列
- 将整个散列传递到
where
。
所以第一步是这样的。
same_conditions_list = [
:plan_comptable,
:budget,
:situation_budget,
:budget_previsionnel,
:exercice_comptable
]
same_conditions_key_values = same_conditions_list.inject({}) do |conditions, condition|
conditions[condition] = { supprime: 'false' }
conditions
end
same_conditions = Hash[same_conditions_key_values]
all_conditions = same_conditions.merge({
immeuble: { id: "place.id" }
})
在那之后 all_conditions
将等于这个
{
:plan_comptable=>{:supprime=>"false"},
:budget=>{:supprime=>"false"},
:situation_budget=>{:supprime=>"false"},
:budget_previsionnel=>{:supprime=>"false"},
:exercice_comptable=>{:supprime=>"false"},
:immeuble=>{:id=>"place.id"}
}
那么第二步就是
::AllocatedBudget.joins(:account_code, :budget, account_code: [:place],
budget: [:fiscal_year, :budget_state])
.where(all_conditions)
关于mysql - Rails 和 ActiveRecord - 重构多个相同的 where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47789311/