Associations and to_json on collections of objects

ActiveRecord’s Serialization module does provide to_json method. It allows include associations when dumping to JSON, but it works only for single objects. If You want to run it against collection, returned by find :all You will get:

>> Model.all.to_json :include =>:association
TypeError: wrong argument type Hash (expected Data)
	from (irb):13:in `to_json'
	from (irb):13

If You want to get in JSON collection with some associations You have to do it manually:

    @companies = Company.all, :include => :address
    render :text => "[ %s ]" % @companies.collect{ |c|
      c.to_json(:include => :address)
    }.join(","),
      :content_type => 'application/json'

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.