开发者

how do I return model parent values when I make a query from the database

开发者 https://www.devze.com 2023-02-06 22:12 出处:网络
So I have a model called Image that belongs_to :user. Each user has a first and last name. I have a flash app that I am returning a json object back to of Images.

So I have a model called Image that belongs_to :user. Each user has a first and last name.

I have a flash app that I am returning a json object back to of Images.

the service I will be calling on the Images controller would look something like this

def getimages
    @images = Image.all
    render :json => @images

  end

My json would look something like 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 I would like to do is also include the users first and last name with in the image object that gets passed back.

once I have an image object I am able to do something like image.user.first_name but I am not clear how I would return 开发者_Go百科something like an array of image objects and include the user along with it.

what would be great is if I could get my array of images to look like the 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 am thinking this may include adding some kind of model method or somthing that I am not familiar with.

What would be the best practice for 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 it works on Arrays). Finally, http://apidock.com/rails/ActionController/Base/render describes using to_json in a json render as optional and not required, which implies it should cause no harm (I couldn't see another way to pass the required options in).

Perhaps cleaner json:

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


Besides the answer provided by @apneadiving, you can also override the Image's to_json method and return a string containing whatever JSON you need.

0

精彩评论

暂无评论...
验证码 换一张
取 消