3

First off, I am not using Rails. I am using Sinatra for this project with Active Record.

I want to be able to override either to_json or as_json on my Model class and have it define some 'default' options. For example I have the following:

class Vendor < ActiveRecord::Base
  def to_json(options = {})
    if options.empty?
      super :only => [:id, :name]
    else
      super options
    end
  end
end

where Vendor has more attributes than just id and name. In my route I have something like the following:

@vendors = Vendor.where({})
@vendors.to_json

Here @vendors is an Array vendor objects (obviously). The returned json is, however, not invoking my to_json method and is returning all of the models attributes.

I don't really have the option of modifying the route because I am actually using a modified sinatra-rest gem (http://github.com/mikeycgto/sinatra-rest).

Any ideas on how to achieve this functionality? I could do something like the following in my sinatra-rest gem but this seems silly:

@PLURAL.collect! { |obj| obj.to_json }
mikeycgto
  • 3,368
  • 3
  • 36
  • 47

2 Answers2

5

Try overriding serializable_hash intead:

def serializable_hash(options = nil)
  { :id => id, :name => name }
end

More information here.

Community
  • 1
  • 1
Brian Deterling
  • 13,556
  • 4
  • 55
  • 59
  • exactly what I need. I like the fact that I could also add in properties that aren't attributes as well. Thanks a ton! – mikeycgto Oct 22 '10 at 19:53
4

If you override as_json instead of to_json, each element in the array will format with as_json before the array is converted to JSON

I'm using the following to only expose only accessible attributes:

def as_json(options = {})
    options[:only] ||= self.class.accessible_attributes.to_a
    super(options)
end
Dan Green
  • 341
  • 3
  • 5