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