Using Rails 3.2, I'm working on an API backed model (not ActiveRecord). I want to be able to call to_json
on this model in Rails controllers. After reading through a bunch of the ActiveModel docs I'm still not clear on one thing:
Given a model like this:
class MyModel
attr_accessor :id, :name
def initialize(data)
@id = data[:id]
@name = data[:name]
end
def as_json
{id: @id, name: @name}
end
end
Should this work as expected, or do I also need to include ActiveModel::Serializers::JSON
? I'm having a hard time figuring out where the as_json
/ to_json
methods are normally defined and when Rails calls which ones automatically in different circumstances...
Thanks for any insight!