Gibt es eine effizientere Möglichkeit, eine Sammlung von Objekten einem Array von Hashes zuzuordnen?
def list
@photos = []
current_user.photos.each do |p|
@photos << {
id: p.id, label: p.name, url: p.uploaded_image.url(:small),
size: p.uploaded_image_file_size
}
end
render json: { results: @photos }.to_json
end
Dies erscheint ein wenig ausführlich, aber die Struktur, die es zurückgibt, wird vom Frontend benötigt.
Aktualisieren
Damit .map
ist die bevorzugte Methode dann?
Antworten:
3 für die Antwort № 1- Tun Sie es nicht im Controller
- Erzeugen Sie nicht die Json-Antwort mit
map
, Lasst unsas_json(*)
Methode machen das für Sie. - Benutze es nicht
@
Variable im Json Render. - Benutze es nicht
{}.to_json
dasrender json: {}
Mach es unter der Haube.
im Fotomodell.
def as_json(*)
super(only: [:id], methods: [:label, :url, :size])
end
alias label name
def size
uploaded_image_file_size
end
def url
uploaded_image.url(:small)
end
Controller-Code.
def list
render json: { results: current_user.photos }
end
1 für die Antwort № 2
Bitte versuche
def list
@photos = current_user.photos.map { |p| { id: p.id, label: p.name, url: p.uploaded_image.url(:small), size: p.uploaded_image_file_size } }
render json: { results: @photos }
end
1 für die Antwort № 3
Als Ausgangspunkt sollte es näher an sein:
def list
@photos = current_user.photos.map do |p|
{
id: p.id, label: p.name, url: p.uploaded_image.url(:small),
size: p.uploaded_image_file_size
}
end
render json: { results: @photos }
end
Nur zum Spaß, du könnte etwas tun wie:
class PhotoDecorator < SimpleDelegator
def attributes
%w(id label url size).each_with_object({}) do |attr, hsh|
hsh[attr.to_sym] = send(attr)
end
end
def label
name
end
def url
uploaded_image.url(:small)
end
def size
uploaded_image_file_size
end
end
Und dann:
> @photos = current_user.photos.map{ |photo| PhotoDecorator.new(photo).attributes }
=> [{:id=>1, :label=>"some name", :url=>"http://www.my_photos.com/123", :size=>"256x256"}, {:id=>2, :label=>"some other name", :url=>"http://www.my_photos/243", :size=>"256x256"}]
0 für die Antwort № 4
Das kannst du auch so machen
def array_list
@photos = current_user.photos.map { |p| { id:
p.id, label: p.name, url: p.uploaded_image.url(:small), size: p.uploaded_image_file_size } }
render json: { results: @photos }
end