【问题标题】:ruby on rails to_json include only countruby on rails to_json 仅包含计数
【发布时间】:2015-05-05 04:21:08
【问题描述】:

简单的例子,我有两个与 has_many_belongs 关联的模型关系

to_json 函数 users_count 如何渲染?

class Place < ActiveRecord::Base 
   has_and_belongs_to_many :users
end


class User < ActiveRecord::Base
   has_and_belongs_to_many :places
end

places = Place.all

render json: {desc:true,  status: 1,  data: places}.to_json(:include => [:users])




output: data[ 
            {
            place_id: 1,
            users[]
            }

我怎样才能这样输出:

output: data[ 
            {
            place_id: 1,
            users_count: 10
            }

我是初学者,可以帮忙吗? )

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    这是如何获取嵌套关系的一个很好的例子:Rails Object Relationships and JSON Rendering

    您似乎想要的不是数据库列,而是计算拥有该位置的所有用户的信息。您可以在 app/models/place.rb 中定义一个函数,如下所示:

    def users_count
      User.where(place_id: id)
    end
    

    然后您可以将其作为以下方法包含在您的数据中:

    render json: {desc:true,  status: 1,  data: places}.to_json(include: :users, methods: :users_count)
    

    这是一个如何在您的to_json 中包含自定义方法的示例:http://www.tigraine.at/2011/11/17/rails-to_json-nested-includes-and-methods

    我以前没有这样做过,所以请告诉我它是如何工作的!

    【讨论】:

    • 你真的帮了我。非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-17
    • 2020-06-14
    • 1970-01-01
    相关资源
    最近更新 更多