Skip to content Skip to sidebar Skip to footer

Filter A Model's Attributes Before Outputting As Json

I need to output my model as json and everything is going fine. However, some of the attributes need to be 'beautified' by filtering them through some helper methods, such as numbe

Solution 1:

Your model can override the as_json method, which Rails uses when rendering json:

# class.rbinclude ActionView::Helpers::NumberHelper
classItem < ActiveRecord::Basedefas_json(options={})
    { :state => state, # just use the attribute when no helper is needed:downloaded => number_to_human_size(downloaded)
    }
  endend

Now you can call render :json in the controller:

@items = Item.all
# ... etc ...
format.json { render :json => @items }

Rails will call Item.as_json for each member of @items and return a JSON-encoded array.

Solution 2:

I figured out a solution to this problem, but I don't know if it's the best. I would appreciate insight.

@items = Item.all

@response = []

@items.each do|item|@response << {
      :state => item.state,
      :lock_status => item.lock_status,
      :downloaded => ActionController::Base.helpers.number_to_human_size(item.downloaded),
      :uploaded => ActionController::Base.helpers.number_to_human_size(item.uploaded),
      :percent_complete => item.percent_complete,
      :down_rate => ActionController::Base.helpers.number_to_human_size(item.down_rate),
      :up_rate => ActionController::Base.helpers.number_to_human_size(item.up_rate),
      :eta => item.eta
  }
end

respond_to do|format|
  format.json { render :json => @response }
end

Basically I construct a hash on the fly with the values I want and then render that instead. It's working, but like I said, I'm not sure if it's the best way.

Post a Comment for "Filter A Model's Attributes Before Outputting As Json"