1

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.

4

1 回答 1

4

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
jbuilder
rabl

You could create a serializer
http://railscasts.com/episodes/409-active-model-serializers

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]
      )
    }
  end
end

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.

Edit:
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]
end
于 2013-03-30T23:29:10.890 回答