1

Simple example, I have two Models relation with has_many_belongs associations

How to render with to_json function 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? )

Undo
  • 25,519
  • 37
  • 106
  • 129

1 Answers1

2

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

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:

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

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

Community
  • 1
  • 1
george
  • 153
  • 7