Take the 2-minute tour ×

I am using Rails 3.

When using respond_with to output JSON/XML/HTML, it dumps all of the attributes by default. What is a good strategy to hide/filter/suppress resource attributes that should not be rendered?

The article here explains what respond_with does.

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

There are a few options.

You can overwrite the as_json method on the model you are working with http://jonathanjulian.com/2010/04/rails-to_json-or-as_json/

You can use a json builder

You could create a serializer

or you could use the :only option on to_json

def index
  @models = Model.all
  respond_with(@models) do |format|
    format.html { render }
    format.json { 
      render json: @models.to_json(
        only: [:some_attribute, :some_other_attribute]

Unless you are using these constraints in many actions I would recommend the last choice (using :only because I believe it to be the simplest but you may feel like the controller isn't the place for this kind of logic.

And there are probably many more ways to do this.

respond_with takes a hash as a second argument to make the above prettier (thanks @ck3g)

def index
  @models = Model.all
  respond_with @models, only: [:some_attribute, :some_other_attribute]
share|improve this answer
The :only option works with respons_with as well. I prefer this solution: respond_with @user, only: [:id, :email, :phone]. It looks much cleaner. –  ck3g Apr 4 '13 at 17:27
Great. It isn't documented (AFAIK). I will update the answer and start using this. Thanks @ck3g –  pferdefleisch Apr 4 '13 at 21:39
add comment

Your Answer


