Search code examples
ruby-on-railsruby-1.9.3downgradeto-json

Downgrading rails project to Ruby 1.9.3 | amusing .to_json trouble


Dear stackoverflow people, I want to downgrade a rails project so it can run on rails 3 without any problems. It worked before on the newest version of rails, but the office does not want to use this one. I have trouble with rewriting this particular line:

@results = @sessions.to_json(:include => [:orientations, :subtopics, :data_files, :participants, :formats, :comments => {:include => [:user => {:only => [:id, :name]}]}])

@sessions are of course a list of results. Is there anyone who knows how I can write an alternative for this that will also run on older versions of rails?

Thanks in advance

Kind regards


Solution

  • Here you go:

    Anytime to_json is called on an object, as_json is invoked to create the data structure, and then that hash is encoded as a JSON string using ActiveSupport::json.encode. This happens for all types: Object, Numeric, Date, String, etc (see active_support/json).

    ActiveRecord objects behave the same way. There is a default as_json implementation that creates a Hash that includes all the model’s attributes. You should override as_json in your Model to create the JSON structure you want. as_json, just like the old to_json, takes an option hash where you can specify attributes and methods to include decoratively.

    def as_json(options={})
      super(:only => [:email, :avatar], :include =>[:addresses])
    end
    

    Your controller code to display one model should always look like this:

    render :json => @user
    

    And if you have to do anything out of the ordinary, call as_json passing your options.

    render :json => { :success => true, 
      :user => @user.as_json(:only => [:email]) }
    

    The moral of the story is: In controllers, do not call to_json directly, allow render to do that for you. If you need to tweak the JSON output, override as_json in your model, or call as_json directly.

    Fix your code now to use as_json - it will be one less thing to worry about when you migrate to Rails 3 or Ruby 1.9.3.