I figured out how to include the children in a to_json result by creating an as_json method in the folder model.
def as_json(options={ })
super(
options.merge(
:include => {
:children => { }
}
)
)
end
The above code gives me a list of the children, but what I want is to include the count not the list of children. I also want to filter it to only “Active” children.
I can’t seem to figure out an efficient way to do this.
I’m using the below code to return a list of folders.
def index
@folders = Folder.all(:order => "Name")
respond_with(@folders) do |format|
format.jsonp { render :json => @folders, :callback => params[:callback] }
end
end
Finally, I want to make sure the count comes back in all results not just json. json is the most important but I do want to make sure it’s in the others as well.
I thought I would be able to add the count to each of the folders returned by @folders after the query by using .size. However, that doesn’t seem to work…
Next I started looking into adding a method to the Folder model such as…
def child_count
write_attribute(:child_count, children.size)
end
But after looking at it I realized that’s not really going to work…
So now I’m looking into :select to do some sql magic… but I really don’t want to go that route if there’s a cleaner way.
Tips appreciated!
Just add a
child_countmethod that returns the number of children and then use the:methodsoption foras_json:You might want to be a bit more careful with that
mergethough, if there is a:methodsalready inoptionsyou’ll overwrite it; something like this might serve you better than a straight merge:For XML, you do pretty much the same thing with
to_xmlinstead ofas_json.