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? )

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.