简体   繁体   中英

Return time difference in method as JSON

I return all information in a scream as JSON.

I want to return how long ago it was created.

include ActionView::Helpers::DateHelper

def as_json(options={})
  super(:only => [:id, :yell_type, :status, :payment_type],
        :include => {
            :trade_offer => {:only => [:id, :title, :description, :price],
                             :include => [:photos => {:only => [:id, :url]}]
            },
            :categories => {:only => [:id, :name]},
            :user => {:only => [:id, :name, :avatar]}
        },
        :methods => [ times_ago(:create_at) ]
  )
end

def times_ago(create_at)
  time_ago_in_words(create_at)
end

This returns an error:

comparison of Symbol with Time failed

How should I do that?

You can add methods on the same level as include and only . So the return value of the method will be passed in the JSON too. In this case, you should implement a method times_ago in the model that returns what you want.

def as_json(options={})
  super(
    :only => [:id, :yell_type, :status, :payment_type],
    :include => {
        :trade_offer => {:only => [:id, :title, :description, :price],
                         :include => [:photos => {:only => [:id, :url]}]
        },
        :categories => {:only => [:id, :name]},
        :user => {:only => [:id, :name, :avatar]}
    },
    :methods: [ :times_ago ]
  )
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM