views:

319

answers:

2

I have a fairly large model and I want to retrieve only a select set of fields for each record in order to keep the JSON string I am building small.

Using :select with find works great but my key goal is to use conditional logic with an associated model. Is the only way to do this really with a lamda in a named scope? I'm dreading that perhaps unnecessarily but I'd like to understand if there is a way to make the :select work with a condition.

This works:

@sites = Site.find  :all, :select => 'id,foo,bar'

When I try this:

@sites = Site.find  :all, :select => 'id,foo,bar', :include => [:relatedmodel],
                  :conditions => ["relatedmodel.type in (?)", params[:filters]]

The condition works but each record includes all of the Site attributes which makes my JSON string way way too large.

Thanks for any pointers!

+1  A: 

The to_json call supports :except and :only options to exclude/include model fields during serialization.

@sites.to_json(:only => [:name, :foo, :bar])

Call above serializes the Site objects with fields name and location.

@sites.to_json(:only => [:name, :location], 
        :include => { :relatedmodel => { 
                          :only => [:description] 
                      } 
                    }
         )

Call above serializes the Site objects with fields name, and location and contained RelatedModel objects with description field.

KandadaBoggu
This is great. I didn't think about looking at the to_json call as I was hung up on trying to get activerecord to give me what I wanted. This works perfectly and my JSON object is now a reasonable size. Thanks!
Nick
A: 

I'm having the same issue, but this method does't work when including multiple associations:

@thing.to_json(:include => [:this, :that, :the_other => {:except => [:this_field]}])

Any ideas?

Corey Tenold