rails to_json上的ruby仅包括count

时间:2022-12-08 23:21:32

Simple example, I have two Models relation with has_many_belongs associations

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

How to render with to_json function users_count?

如何使用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[]
            }

How can I output like this:

我该如何输出:

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

I am beginner, please can you help? )

我是初学者,请帮忙吗? )

1 个解决方案

#1


This is a good example of how to get the nested relationships: Rails Object Relationships and JSON Rendering

这是如何获得嵌套关系的一个很好的例子:Rails对象关系和JSON渲染

It seems you want not a database column, but information that counts all the users that have that place. You could define a function in your app/models/place.rb that looks like:

您似乎不想要数据库列,而是要计算具有该位置的所有用户的信息。您可以在app / models / place.rb中定义一个看起来像这样的函数:

def users_count
  User.where(place_id: id)
end

Then you can include this in your data as a method like:

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

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

Here is an example of how to include custom methods in your to_json: http://www.tigraine.at/2011/11/17/rails-to_json-nested-includes-and-methods

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

I haven't done this before so let me know how it works!

我之前没有这样做过,所以让我知道它是如何工作的!

#1


This is a good example of how to get the nested relationships: Rails Object Relationships and JSON Rendering

这是如何获得嵌套关系的一个很好的例子:Rails对象关系和JSON渲染

It seems you want not a database column, but information that counts all the users that have that place. You could define a function in your app/models/place.rb that looks like:

您似乎不想要数据库列,而是要计算具有该位置的所有用户的信息。您可以在app / models / place.rb中定义一个看起来像这样的函数:

def users_count
  User.where(place_id: id)
end

Then you can include this in your data as a method like:

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

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

Here is an example of how to include custom methods in your to_json: http://www.tigraine.at/2011/11/17/rails-to_json-nested-includes-and-methods

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

I haven't done this before so let me know how it works!

我之前没有这样做过,所以让我知道它是如何工作的!