Providing JSON in Phoenix

I used "mix phoenix.gen.json" to generate the code for json rendering, resulting in the following:

defmodule Pghm.SightingsView do    
  use Pghm.Web, :view

  def render("sighting.json", %{sighting: sighting}) do
    %{what: sighting.what,
      lat:  sighting.lat,
      long: sighting.long}
  end

  def render("index.json", %{sightings: sightings}) do
    %{data: render_many(sightings, Pghm.SightingsView, "sighting.json")}
  end

  def render("show.json", %{sighting: sighting}) do
    %{data: render_one(sighting, Pghm.SightingsView, "sighting.json")}
  end
end

However, when I try to access the call, I get: Failed to display "sighting.json" for Pghm.SightingsView, please determine the appropriate sentence for render / 2 or define the template in "web / templates / sightings". No templates were compiled for this module. Assigns:

Wherever I looked indicates that this should work, but I do not get love.

+4
source share
2 answers

I recently started with Phoenix, but I probably know what the problem is.

def render("sighting.json", %{sighting: sighting}) do
  %{what: sighting.what,
    lat:  sighting.lat,
    long: sighting.long}
end

, , :

render("sighting.json", %{sighting: some_data})

:

%{data: render_many(sightings, Pghm.SightingsView, "sighting.json")}

, , {{sighting: sighting}. , Elixir , .

def render("sighting.json", %{sighting: sighting}) do

def render("sighting.json", sighting) do

.

+8

, , , , Rails.

Phoenix (1), .

- . :        render_many users, UserView, "show.html"  :

Enum.map(users, fn user ->
  render(UserView, "show.html", user: user)
end)

:user, . :as

(1) https://github.com/phoenixframework/phoenix/blob/8a6beef9e13f049a8458db25b71fb70afae7673a/lib/phoenix/view.ex#L267

, :

defmodule Pghm.SightingView do    
  use Pghm.Web, :view

  def render("sighting.json", %{sighting: sighting}) do
    %{what: sighting.what,
      lat:  sighting.lat,
      long: sighting.long}
  end

  def render("index.json", %{sightings: sightings}) do
    %{data: render_many(sightings, Pghm.SightingView, "sighting.json")}
  end

  def render("show.json", %{sighting: sighting}) do
    %{data: render_one(sighting, Pghm.SightingView, "sighting.json")}
  end
end
+1

Source: https://habr.com/ru/post/1648184/


All Articles