【问题标题】:How to send the count value using JSON in ROR如何在 ROR 中使用 JSON 发送计数值
【发布时间】:2013-06-15 05:00:42
【问题描述】:

我想发送计数值,以计算我在 ROR 中使用 thumbs up gem 的帖子。

现在我想在 json 中发送计数,投票作为 def show 中的发布操作

def index
@posts = Post.all
respond_with(@posts) do |format|
  format.json { render json: @post_names = {:post => @posts.as_json(:only=> [:content, :title]) } }

end
end 

我想使用 json 发送计数值,因为我想在客户端显示该计数值。

【问题讨论】:

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


    【解决方案1】:

    您可以通过这种方式发送投票计数。我认为这样的事情可以工作..

    def index
      @posts = Post.all
      respond_with(@posts) do |format|
        format.json { render :json => @post_names = {:post => @posts.map {|t| {:title => t.title, :content => t.content, :count => t.votes_for }} } }
      end
    end
    

    【讨论】:

      【解决方案2】:

      由于您正在使用控制器,您可能会发现查看render section of the Rails documentation 会有所帮助。

      【讨论】:

      • ,不,老兄,实际上投票我使用的是拇指宝石,如何在 json 中发送该计数
      • Ezekiel 是对的——如果你想发送 JSON,你渲染 json。您在这里设置了 ton 的实例变量,因此除非所有这些变量都将成为巨大 JSON 响应的一部分,否则您需要一个单独的控制器方法,只发回您想要的数据。
      猜你喜欢
      • 2012-09-14
      • 1970-01-01
      • 2015-09-30
      • 1970-01-01
      • 1970-01-01
      • 2019-03-29
      • 2016-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多