I'm trying to monkeypatch a method onto ActiveRecord::QueryMethods
which augments the select clause instead of replacing it entirely.
I tried:
# config/initalizers/select_also.rb
module SelectAlso
def select_also(*fields)
select(self.select_values + fields)
end
end
ActiveRecord::QueryMethods.include(SelectAlso)
But this gives me:
/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)
I don't get where its getting the constant ActiveRecord::Relation::QueryMethods
from at all since i'm not referencing it.
The reason I'm doing it as a monkeypatch is that I want to try it out as a potential PR / feature request to rails itself without working on the rails source and dealing with setting up a sample app.
The use case is where you want to add something like aggregates or joined columns without recreating the entire select clause:
User.joins(:answers)
.select_also('AVG(answers.score) AS average_score')
Instead of:
User.joins(:answers)
.select('users.*','AVG(answers.score) AS average_score')
Or some hacky solution that introspects on the table.