I’m trying to implement autocomplete that lets user to pick from list of 2 different kind of models.
This is how my controller looks:
def ac
arr = []
arr << Foo.all
arr << Bar.all
render json: arr.to_json
end
Which renders:
[[{"id":1, "name":"foo name"}], [{"id":1, "name":"bar name"}]]
How to include class name and get something like this:
[
[{"id":1, "name":"foo name", "class_name":"Foo"}],
[{"id":1, "name":"bar name", "class_name":"Bar"}]
]
?
If you don’t mind doing a bit of extra work you can do smth like that with
:methodsoption ofas_jsonmethod (andto_jsonas well):If you have
ActiveRecord::Base.include_root_in_jsonset totrue(that is default afaik) then you’ll get hashes likeIf you want it to be exactly the class name you can pass
:rootoption:Note that both these solutions do not allow you simply to call
to_jsonon an array of records. To overcome that and makeclass_nameincluded by default you can overrideserializable_hashmethod in your model like that:If you wrap it into a module you can include it in any model you want and get
class_nameincluded into the result ofas_jsonorto_jsonwithout passing any extra options to these methods. You can modify the implementation a bit to respect:exceptoption if you want to excludeclass_namein some cases.