Q:

Why does 'as_json' return the whole object instead of simple text?

I am trying to make an API which sends the information to an iOS application using JSON.
My controller has an method called `index:
def index
  @news = News.all
  @banners = News.get_news_banners @news
  render json: { all_news: @news.as_json( only: [:id, :headline], include: [:thumbnail]),        success: true, banners: @banners.as_json }
end

The News model has an method called thumbnail which I am passing to as JSON method:
def thumbnail
  image_multimedia = self.multimedia.where(file_type: Multimedia.file_types[:picture]).all
  if image_multimedia.empty?
    self.banners.last.image_file.url(:preview)
  else
    image_multimedia.each do |m|
      m.asset.url(:preview)
    end
  end
end

The JSON received looks like:
{
 all_news: [1]
 0:  {
  id: 4
  headline: "some new"
  thumbnail: [1]
  0:  {
  id: 4
  server_location: null
  created_at: "2014-10-14T13:13:33.000Z"
  updated_at: "2014-10-14T13:13:33.000Z"
  asset_file_name: "Screenshot_from_2014-09-25_11_10_41.png"
  asset_content_type: "image/png"
  asset_file_size: 6785
  asset_updated_at: "2014-10-14T13:13:33.000Z"
  storable_type: "News"
  storable_id: 4
  file_type: null
  }-
  -
  }-
  -

I want my method to return only the URL, not the whole object data.

A:

You're much better off to use ActiveModel::Serializers for this.
with AMS you'd be able to simply do:
class NewsSerializer < ActiveModel::Serializer
  attributes :url
end

Then in your controller you'd just do:
  respond_to do |format|
    format.html
    format.json { render json: @news }
  end

With ActiveModel::Serializers you can specify what the JSON should contain very simply by utilizing the attributes method.

