steventnorris
steventnorris

Reputation: 5896

Two different as_json methods

I'd like to have my json render in two different ways. I now have my as_json method overridden to display a full object in json form like this:

{
    prop1: stuff,
    prop2: stuff,
    innerthings: {
        {
            prop1:stuff,
            prop2:stuff
        }
        {
            prop1:stuff,
            prop2:stuff
        }
    }
}

And the as_json looks like:

  #Renders json
  def as_json(options={})
    super(
        :except => [:created_at, :updated_at],
        :include => [{:innerthings = > {
                :except => [:created_at, :updated_at]
}}]

    )
  end

I'd also like to have a second option to render like this:

{
    prop1:stuff,
    prop2:stuff,
    countinnerthings:10
}

current when the code below is used, I get the first render:

respond_to do |format|
  format.json { render json: @thing}
end

I'd also like to be able to render with something like as_list that I could use in a case like the below to render just a simple list of the objects.

respond_to do |format|
    format.json { render json: @things.as_list }
end

Is there a simple way to do this in ruby on rails?

Upvotes: 0

Views: 635

Answers (2)

Frederick Cheung
Frederick Cheung

Reputation: 84114

You can just define an as_list method

def as_list
   {
    prop1: "stuff"
   }
end

If you need to use includes etc you can call as_json from your at_list method. As had been said serializers are a better option in general.

Upvotes: 1

eabraham
eabraham

Reputation: 4164

Instead of rolling your own as_json method. Take a look at ActiveModel Serializers. I think it will satisfy you use-case and help organize your code.

Upvotes: 3

Related Questions