jävi
jävi

Reputation: 4565

Overriding as_json method with params

First of all, I'm using Rails 3.0.6 and Ruby 1.9.2

I have a controller with two different actions, both should return a json object, but with different formats. Therefore I'm overriding the as_json method to write the JSON object in my own format. Problem is that I don't know how to pass params to as_json method since it's being automatically called by Rails.

My code looks like this:

class MyController < ApplicationController
  def action1
    # my code
    respond_to do |format|
      # Render with :json option automatically calls to_json and this calls as_json
      format.js  { render :json => @myobjects }
    end
  end

  def action2
    # a different code
    respond_to do |format|
      # This action should return a JSON object but using a different format
      format.js  { render :json => @myobjects }
    end
  end

end



class MyModel < ActiveRecord::Base
  def as_json(options = {})
    # I would like to add a conditional statement here
    # to write a different array depending on one param from the controller
    {
      :id => self.id,
      :title => self.description,
      :description => self.description || "",
      :start => start_date1.rfc822,
      :end => (start_date1 && start_date1.rfc822) || "",
      :allDay => true,
      :recurring => false
    }
  end

end

Note that @myobjects are a collection of objects which class is MyModel.

Any help would be appreciated. Thank you!

Upvotes: 1

Views: 2220

Answers (1)

iafonov
iafonov

Reputation: 5192

Call it explicitly in controller and pass params. as_json will return string and calling as_json on string returns itself. It is quite common practice.

respond_to do |format|
  # Render with :json option automatically calls to_json and this calls as_json
  format.js  { render :json => @myobjects.as_json(params) }
end

Upvotes: 2

Related Questions