2013-06-29 97 views
1

我有一個視圖文件(show.json.erb)顯示我的@step模型屬性,並且我想格式化DateTime屬性「published_on」。以我目前的實現中,我得到的錯誤:爲json格式化日期時間

undefined method `strftime' for :published_on:Symbol 

這裏是我的代碼:

{ 
    "success":true, 
    "info":"ok", 
    "data": 
     { "step": 
      <%= JSON.pretty_generate(@step.as_json(only: [:name, :description, :id, :last, :position, :published_on.strftime("%m/%d/%Y %H:%M:%S")], include: {images: {only: [:file, :position] } })).html_safe %> 
    } 
} 

對於如何解決這個錯誤任何想法?

回答

0

我在我的模型解決了這個被定義的屬性:

def formatted_date 
    published_on.strftime("%m/%d/%Y %H:%M:%S") 
end 

然後,我引用它在我的JSON文件:

<%= JSON.pretty_generate(@step.as_json(only: [:name, :description, :id, :last], methods: :formatted_date, include: {images: {only: [:file, :position] } })).html_safe %>