如何在凤凰丹药中显示参考文献二

How to display references two deep in phoenix elixir

我想在 Pheonix Elixirr 中显示两个 table 的参考资料,似乎离实际获得它还有一步之遥。

有3个相互关联的table:

主要table是客户。客户有请求。请求有 Requesttypes,这是一个查找 table.

在客户模板中要显示客户提出的请求列表。在Show Template中,有一个循环如下:

  <ul>
     <%= for request <- @client.requests do %>

       <%= request.request_date %> - 
       <line in question> -
       <%= request.notes %>&nbsp;

       <%= link "Show", to: Routes.client_request_path(@conn, :show, @client, request) %>&nbsp;
       <%= link "Edit", to: Routes.client_request_path(@conn, :edit, @client, request) %>
     <% end %>
  </ul>

以上内容在没有相关行的情况下工作正常。我想添加从下拉列表中选择的请求类型,因此来自 Request table.

的引用

如果我尝试添加: <%= request.requesttype.requestname => 没用。

在请求展示页面 <%= @requesttype.requestname => 有效

在相关行中 <%= request.requesttype_id %> 是否显示正确的 ID。

错误是key :requesttype not found in: #Ecto.Association.NotLoaded<association :requesttypes is not loaded>.

get_client函数如下:

def get_client!(id, tenant) do 
Client 
|> Repo.get!(id, prefix: Triplex.to_prefix(tenant)) 
|> Repo.preload([:genders, :requests]) 
end 

如何从请求中添加关联 table?

如有任何帮助,我们将不胜感激。

正如错误消息所暗示的那样,嵌套的 requesttypes 没有加载,因为您只预加载了 client.requests,而不是关联的 requesttypes。您需要明确预加载的内容,这实际上是一件好事,因为您可以控制查询的内容。

使用 Repo.preload([genders: [], requests: :requesttypes]) 应该可以解决您的问题,它使用关键字列表预加载嵌套关联,如 one of these doc examples.

请注意,这将触发 4 个单独的查询(根据您的用例,这可能会好或不好),如果您想使用连接来避免这种情况,您可能应该编写一个查询(参见 this great explanation ).

我鼓励您 fiddle 在 REPL (iex -S mix) 中进行查询,它非常透明,您会看到:

  • 返回的数据(加载或不加载)
  • 来自调试日志的基础查询

Elixir 学校中有一个关于此的 great section 也可能很有趣。