现在我的控制器遵循index
方法(将实际模型混淆为Alpha
和Beta
以获得清洁度):
def index
@alphas = Alpha.select('"alphas".*, (SELECT MAX(number) FROM betas WHERE alpha_id = "alphas".id) as max_betas_number')
end
生成的SQL很好,我甚至可以ORDER BY
max_betas_number
列:
SELECT "alphas".*, (SELECT MAX(number) FROM betas WHERE alpha_id = "alphas".id) as max_betas_number FROM "alphas" ORDER BY max_betas_number DESC
问题#1:这是正确的做法吗?
虽然此查询可以正常工作,但在我尝试.paginate()
然后我的整个select包含在COUNT()
中,产生无效的SQL语法:
SELECT COUNT("alphas".*, (SELECT MAX(number) FROM betas WHERE alpha_id = "alphas".id) as max_betas_number) FROM "alphas" ORDER BY max_betas_number DESC
导致:
ERROR: syntax error at or near "as"
LINE 1: ...(number) FROM betas WHERE alpha_id = "alphas".id) as max_bet...
^
问题2:这是will_paginate
宝石的问题,还是直接依赖于我的错误index
方法{{{{{{ 1}}?
答案 0 :(得分:0)
在相应的max_betas_number
模型中考虑缓存 Alpha
。这将使读取查询更简单(并且可能更快,取决于数据量)以每次Beta
修改的额外写入为代价。
开箱即用的ActiveRecord在某些关联上有counter_cache
option (see section 4.3.2)来处理类似情况:它维护关联的对象&#39;计算父模型中的特殊列,例如<assoc>_count
。