Goal: I want to initialize a record like ActiveRecord does under the hood.
Secondary goal: I also want to understand ActiveRecord better.
Why: I want an ActiveRecord object with values that I selected myself using hard-written SQL.
Analogy: I can do
Foo.first
and that will give me a regular Foo instance with all of its columns Foo<id: 1, name: "ABC">
I can also do
Foo.select('1 AS bar').first
and I'll get an instance of Foo that I can then call foo.bar and it will return 1, EVEN if the Foo table doesn't have a 'bar' column. Nice!
Background: I have a hash of properties, {bar 1, id: 1, name: "ABC"}. I want to initialize an instance of Foo that will have a bar property even though the Foo table doesn't have a bar column.
Error: If I try to initialize Foo with those properties, I'll get the error ActiveModel::UnknownAttributeError: unknown attribute 'bar' for Foo
Condition: I don't want to have an attribute :bar in the Foo class, nor do I want an attr_accessor :bar either.
Reasoning: I know that ActiveRecord is doing something under the hood when I select columns that it doesn't have so that in the end I get an object with those properties. What is it doing?