Given:
class Foo
has_one :bar
def bar_name
bar.name
end
end
class Bar
belongs_to :foo
end
In the console or in a view, I can @foo.bar_name
to get 'baz'
.
I'm aware that I can @foo.as_json(methods: :bar_name)
to get {"id"=>"abc123", "bar_name"=>"baz"}
.
I could also denormalize the attribute and make it non-virtual, but I would rather not do that in this case.
Is it possible to automatically return the model with the virtual attribute included?
#<Foo id: "abc123", bar_name: "baz">
I want to do this because I am constructing a large object with nested collections of models, and the as_json
call is abstracted away from me.