Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including a model's virtual attributes when converting a record to JSON in Rails

I'm trying to convert an ActiveRecord model to JSON in Rails, and while the to_json method generally works, the model's virtual attributes are not included. Is there a way within Rails to list not just the attributes of a model, but also it's attr_accessor and attr_reader attributes in order that all readable attributes are available when the model is converted to JSON?

like image 824
joeellis Avatar asked Mar 23 '10 15:03

joeellis


2 Answers

Before Rails 3, use the :method option:

@model.to_json(:method => %w(some_virtual_attribute another_virtual_attribute))

In Rails 3, use :methods option

@model.to_json(:methods => %w(some_virtual_attribute another_virtual_attribute))
like image 150
François Beausoleil Avatar answered Sep 28 '22 02:09

François Beausoleil


I did this to put the information in the model and to keep the method compatible with any way another class might call it (as_json is called by to_json and is supposed to return a Hash):

class MyModel < ActiveRecord::Base
  def as_json options=nil
    options ||= {}
    options[:methods] = ((options[:methods] || []) + [:my, :virtual, :attrs])
    super options
  end
end

(tested in Rails v3.0)

like image 31
clacke Avatar answered Sep 28 '22 00:09

clacke