response_with中属性的内部方法

时间:2012-03-27 06:56:46

标签: ruby-on-rails ruby-on-rails-3 json

我正在使用以下代码呈现序列化的JSON响应:

respond_with(@posts, :only => [:id, :content, :created_at], 
        :include => { :user => { :only => [:id, :name] }, 
                      :comments => { :only => [:content, :created_at] }})

响应是在JAVA代码中解析的,所以我想将created_at值转换为我可以使用的格式,如何在每个created_at值上运行一个方法(例如甚至.to_i)?

2 个答案:

答案 0 :(得分:1)

我会在评论模型中定义一个新方法,例如。

class Comment < ActiveRecode::Base
  ...
  def created_at_to_i
     created_at.to_i
  end 
  ...
end

和渲染时

respond_with(@posts, :only => [:id, :content, :created_at], 
        :include => { :user => { :only => [:id, :name] }, 
                      :comments => { :only => [:content, :created_at_to_i] }})

答案 1 :(得分:0)

在每个模型中定义方法,如:

def formated_created_at
  self.created_at.strftime(FORMAT_AS_YOU_LIKE)
end 

在渲染时使用它像:

  

respond_with(@ postts,:only =&gt; [:id,:content,:formated_created_at   ,           :include =&gt; {:user =&gt; {:only =&gt; [:id,:name]},:comments =&gt; {:only =&gt; [:content,:formated_created_at   ]}}})

已编辑:

您可以创建自己的哈希并将其传递给respond_with,而不是仅使用:在respond_with中。 喜欢:

post_hash= { :post => [{:id => 1, :content => "abc", :created_at => self.formated_created_at,:user => {:id => 1, :name => 'Vik' }, :comments => { :content => "comment text", :created_at => self.comment.formated_created_at}] }
respond_with(post_hash)

我认为你可以通过javascript,jQuery在显示时格式化created_at。