ruby on rails - how do I return model parent values when I make a query from the database -


so have model called image belongs_to :user. each user has first , last name.

i have flash app returning json object of images.

the service calling on images controller this

def getimages     @images = image.all     render :json => @images    end 

my json this

[{"image":{"created_at":"2011-01-22t19:04:30z","img_path":"assets/img/bowl_93847566_3_0.png","updated_at":"2011-01-22t19:04:30z","id":9,"user_id":3}}] 

what include users first , last name in image object gets passed back.

once have image object able image.user.first_name not clear how return array of image objects , include user along it.

what great if array of images following.

[{"image":{"created_at":"2011-01-22t19:04:30z","img_path":"assets/img/bowl_93847566_3_0.png","updated_at":"2011-01-22t19:04:30z","id":9,"user_id":3, "first_name":"matthew", "last_name":"wallace"}}] 

i thinking may include adding kind of model method or somthing not familiar with.

what best practice achieving this?

you could:

render :json => @images.to_json(:include => :users) 

see http://apidock.com/rails/activerecord/serialization/to_json (and http://apidock.com/rails/array/to_json shows works on arrays). finally, http://apidock.com/rails/actioncontroller/base/render describes using to_json in json render optional , not required, implies should cause no harm (i couldn't see way pass required options in).

perhaps cleaner json:

render :json => @images.to_json(:include => { :user => { :only => [:first_name, :last_name] } }) 

Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -