Format date time in find operation in Rails 3

前端 未结 6 1736
情话喂你
情话喂你 2021-01-28 15:34

I\'m looking for a way to format date time in find(:all) so that when I render my results in JSON, the date time will look like

\"March 20, 2011\"

instead of

6条回答
  •  不知归路
    2021-01-28 16:05

    OK, so you want to render the results in JSON formatted nicely. Instead of changing the format of the date on the way in, change it on the way out.

    class Post
    
      def formatted_created_at
        created_at.strftime("%b %d, %Y")
      end
    
      def as_json(args={})
        super(:methods=>:formatted_created_at, :except=>:date)
      end
    end
    

提交回复
热议问题