if condition1
ModelName.named_scope1(parameter).named_scope2.named_scope3(parameter).named_scope4
elsif condition2
ModelName.named_scope1(parameter).named_scope2.named_scope3(parameter).named_scope5
elsif condition3
ModelName.named_scope1(parameter).named_scope2.named_scope3(parameter).named_scope6
elsif
ModelName.named_scope1(parameter).named_scope2.named_scope3(parameter).named_scope7
end
To solve the above issue I have written it something like this but it fires two queries.
values = ModelName.named_scope1(parameter).named_scope2.named_scope3(parameter)
if condition1
values.named_scope4
elsif condition2
values.named_scope5
elsif condition3
values.named_scope6
elsif
values.named_scope7
end
Any solution ?
Your first and second examples do exactly the same thing, so the original implementation must have also been sending two queries. I think your pseudo-code is a little too generic to comment further, but generally when I have lists of if..elsif..else conditions (or long case..when's for that matter), I try to consider if I could use a lookup table (just a Hash) instead. It may not directly apply to your example, however.
So instead of something like this:
case value
when "one"
obj.do_something(1, 2, 3)
when "two"
obj.do_something(4, 5, 6)
when "three"
...
end
Re-think it as:
args_map = {
"one" => [1, 2, 3],
"two" => [4, 5, 6],
"three" => ...
}
obj.do_something(*args_map[value])
您可以构建动态范围,尽管在不确切知道如何确定范围选择标准的情况下,很难说出动态范围代码可能在哪里 ,或者明显的解决方案(您自己)是否更清楚。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.