I’ve followed Ryan Bates’ screencast on using jQuery Tokeninput for an auto-completing list for a many-to-many association. Now I want to pull in a photo for each result. I’m using Paperclip and get the url’s passed into a JSON file by doing this in the controller:
format.json { render :json => @users.map(&:photo_url) }
Ryan’s code for passing the attributes into a JSON file is this:
format.json { render :json => @users.map(&:attributes) }
But how can I combine the two to display both the :attributes and :photo_url methods in the JSON file?
I’ve tried different things, including the below code, but nothing seems to work. It seems as if there can only be one method called on .map?
// Doesn't work
format.json { render :json => @users.map(&:attributes, &:photo_url) }
// Doesn't work
format.json { render :json => @users.map(&:attributes).map(&:photo_url) }
Does this help? (Note – I’m just returning from a night out and am not 100%, so I might be misunderstanding your question entirely.)
This creates an array of arrays: The first element in the array contains the user’s attributes, and the second contains the photo URL:
@users.map {|u| [u.attributes, u.photo_url]}
This creates a hash – just like the above array. But the first element is named “attributes” and the second is named “photo_url”.
@users.map {|u| {:attributes => u.attributes, :photo_url => u.photo_url}}
Try plugging one or both of those in. They should work for you.
(E.g.
format.json { render :json => @users.map {|u| [u.attributes, u.photo_url]} }).Edit:
Just had another thought.
You can merge the two into one collection (so that you’ll have it all in one hash instead of separate elements in an array):
@users.map {|u| u.attributes.merge(:photo_url => u.photo_url)}
That’ll add
photo_urlas a key to theattributeshash. It might work more easily for whatever code you’ve written to read the JSON.