ruby-on-rails - 如何猴子补丁 ActiveRecord::QueryMethods?
问题描述
我正在尝试修补一种方法,在ActiveRecord::QueryMethods
该方法上增加 select 子句,而不是完全替换它。
我试过了:
# config/initalizers/select_also.rb
module SelectAlso
def select_also(*fields)
select(self.select_values + fields)
end
end
ActiveRecord::QueryMethods.include(SelectAlso)
但这给了我:
/lib/ruby/gems/2.6.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/active_support.rb:79:in `block in load_missing_constant': uninitialized constant ActiveRecord::Relation::QueryMethods (NameError)
ActiveRecord::Relation::QueryMethods
因为我没有引用它,所以我根本不知道它从哪里得到常量。
我将其作为猴子补丁进行操作的原因是,我想将其作为对 rails 本身的潜在 PR / 功能请求进行尝试,而无需处理 rails 源代码并处理设置示例应用程序。
用例是您想要添加聚合或连接列等内容而不重新创建整个 select 子句的地方:
User.joins(:answers)
.select_also('AVG(answers.score) AS average_score')
代替:
User.joins(:answers)
.select('users.*','AVG(answers.score) AS average_score')
或者一些在桌面上自省的 hacky 解决方案。
解决方案
您可能需要考虑ActiveRecord::QueryMethods#extending
作为猴子修补的替代方案 - 它旨在通过其他方法扩展范围。
module Pagination
def page(number)
# pagination code goes here
end
end
scope = Model.all.extending(Pagination)
scope.page(params[:page])
Rails 还支持对关联应用扩展,这非常简洁。
推荐阅读
- reactjs - reactjs 中 ng-init 的等价物
- python - Pyspark DF groupBy 给出错误 - TypeError: 'NoneType' object is not iterable
- python - os.getcwd() 找不到当前工作目录
- javascript - 在本机反应中不断收到“无法解析模块”
- apache-spark - 在 log4j.properties 文件中使用 %throwable 的异常 Stacktrace 日志未完全加载
- amazon-web-services - 当新项目进入队列时触发 Fargate
- for-loop - For Loop 复制 Postman 数据文件中的结果 - 使用 Collection Runner
- spring - Spring Boot 上的 ActiveMQ 身份验证
- rdf - 我可以使用 skos:broader 关联两个 skos:ConceptScheme 吗?
- sql-server - 如何在 sql server 设置中全局设置 ansi_warnings 和 ansi_padding?