aBadAssCowboy
aBadAssCowboy

Reputation: 2520

include no.of associations in to_JSON rails

i have a relation in rails models like this , subject has many units and units have many questions. So in controller returning response like this

    @response = subject.as_json()
@response["units"] = subject.units.to_json()

now in this i want to include the count of number of questions available in those each units of that subject.

doing this

    @response["units"] = subject.units.to_json(:include => :questions)

will give include a array of all the questions in that unit.. but i need only the count to be sent.

I can actually write a method in units controller to return questions count but that is not very feasible for me. So, let me know if it is possible to include count directly through :include.

Thanks in advance

Upvotes: 0

Views: 190

Answers (1)

John H
John H

Reputation: 2488

The problem is that you're going to run a count on the questions table every time you do this.

You should look into the counter_cache feature in Rails. Since you're going to want this value every time you get this response it makes sense to cache the count on the parent unit rather than run a count every time.

Docs: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-belongs_to-label-Options

Railscast: http://railscasts.com/episodes/23-counter-cache-column

Just by the by, you'll get more and better answers if you increase your accept rate. It's very low at 29%.

Upvotes: 1

Related Questions