ruby on rails - Why does 'as_json' return the whole object instead of simple text? -



ruby on rails - Why does 'as_json' return the whole object instead of simple text? -

i trying create api sends info ios application using json.

my controller has 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 method called thumbnail passing 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 |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 method homecoming url, not whole object data.

you're much improve off utilize activemodel::serializers this.

with ams you'd able do:

class newsserializer < activemodel::serializer attributes :url end

then in controller you'd do:

respond_to |format| format.html format.json { render json: @news } end

with activemodel::serializers can specify json should contain utilizing attributes method.

ruby-on-rails ruby json api ruby-on-rails-4

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -