mjc
mjc

Reputation: 3426

Active Record to_json\as_json on Array of Models

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 }

Upvotes: 3

Views: 4722

Answers (2)

Dan Green
Dan Green

Reputation: 341

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

Upvotes: 4

Brian Deterling
Brian Deterling

Reputation: 13724

Try overriding serializable_hash intead:

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

More information here.

Upvotes: 5

Related Questions