Ruby on Rails + Active_Record: How do I include child counts in result?
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_count
method that returns the number of children and then use the :methods
option for as_json
:
def as_json(options = { })
super(options.merge(:methods => :child_count))
end
You might want to be a bit more careful with that merge
though, if there is a :methods
already in options
you'll overwrite it; something like this might serve you better than a straight merge:
def add_child_count(options)
options[:methods] = [ options[:methods], :child_count ].flatten.compact.uniq
options
end
def as_json(options = { })
super(add_child_count(options))
end
For XML, you do pretty much the same thing with to_xml
instead of as_json
.
精彩评论