Render many to many relationship JSON in Phoenix Framework

﹥>﹥吖頭↗ 提交于 2019-11-27 21:38:32

Using render_many/4 is correct.

If you wish to define the "role.json" render function in the same module you can do:

def render("user.json", %{user: user}) do
  %{
    id: user.id,
    name: user.name,
    roles: render_many(user.roles, __MODULE__, "role.json", as: :role)
  }
end

def render("role.json", %{role: role}) do
  %{
    id: role.id
    ... 
  }
end

Notice that we pass as: :role to the render_many function. This is because the assigns (the %{role: role}) part is inferred from the view name. In this case it is the UserView so it would be %{user: user} by default.

If you define a RoleView module then you can just move the def render("role.json") function to your new RoleView and call render_many without the as option:

...
roles: render_many(user.roles, MyApp.RoleView, "role.json")
...

Another option that may be preferable for you is to derive a protocol in your model:

defmodule App.Role do
  use App.Web, :model
  @derive {Poison.Encoder, only: [:id, :name]}

  schema "roles" do
    has_many :roles_users, App.RolesUser
    has_many :users, through: [:roles_users, :user]
    field :name, :string
    timestamps
  end

Personally I feel this couples your model to your view, so I prefer to use the first option.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!