/ / Effiziente Methode zum Konvertieren der Sammlung in ein Array von Hashwerten für Render-Json - Ruby-on-Schienen, Arrays, Ruby, Ruby-on-Schienen-5

Effiziente Methode zum Konvertieren von Sammlungen in Hash-Arrays für Render-JSons - Ruby-on-Rails, Arrays, Ruby, Ruby-on-Rails-5

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
  1. Tun Sie es nicht im Controller
  2. Erzeugen Sie nicht die Json-Antwort mit map, Lasst uns as_json(*) Methode machen das für Sie.
  3. Benutze es nicht @ Variable im Json Render.
  4. Benutze es nicht {}.to_json das render 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