1

在过去的几天里,我一直在阅读并熟悉 handlebars.js 模板,这很棒。

现在我正在使用我的一个部分,它有一堆 html,我在其中使用了诸如 simple_format、time_ago_in_words 等助手。显然,这些助手不能与车把一起使用。所以我想做这样的事情:

def get_micropost

   respond_to do |format|   
     format.json { render json: formatted_micropost_json_data(Micropost.where("id < ?", params[:micropost_id]).first) } 
   end

end

微博助手:

module MicropostsHelper

    def formatted_micropost_json_data(micropost)

        content: simple_format h(micropost.content)
        created_at: time_ago_in_words(micropost.created_at)
        id: micropost.id
        image: micropost.image
        link: micropost.link
        poster_id: micropost.poster_id
        updated_at: micropost.updated_at 
        user_id: micropost.user_id 

    end

end

因此,当我通过 ajax 调用返回 JSON 时,它的格式已经正确。然后我可以简单地像往常一样显示我的车把变量。

这甚至会起作用吗?

如果不是,最好的方法是什么?

亲切的问候

4

1 回答 1

4

这是我建议的代码重写:

class Micropost
  def formatted_json_data
    {
      content:    simple_format(h(self.content)),
      created_at: time_ago_in_words(self.created_at),
      id:         self.id,
      image:      self.image,
      link:       self.link,
      poster_id:  self.poster_id,
      updated_at: self.updated_at,
      user_id:    self.user_id
    }
  end
end

def get_micropost
  respond_to do |format|   
    format.json do
      posts = Micropost.where("id < ?", params[:micropost_id])
      data = posts.first.formatted_json_data
      render(json: data)
    end
  end
end

You wanted to your a hash literal inside your method - what you had originally was not syntactically-valid ruby code.

Also breaking up the long line of chained method calls might make for more informative error messages and provide clearer opportunities to handle them.

于 2012-05-24T16:55:17.187 回答