Ich habe eine invoice
welche has_many line_items
die auch zu products
gehört. Unter invoice#show
möchte ich alle line_items
dieser invoice
mit der name
der zugehörigen product
anzeigen. Von Rails kommend fällt es mir schwer, die Punkte zu verbinden. in der Vorlage funktioniert nicht. Wie kann ich den Namen des Produkts in dieser Tabelle anzeigen?Anzeige von Attributen einer has_many durch Verbindung
Die Anwendung
mix phoenix.new my_app
cd my_app
mix ecto.create
mix phoenix.gen.html Invoice invoices number
mix phoenix.gen.html Product products name price:integer
mix phoenix.gen.html LineItem line_items invoice_id:references:invoices
product_id:references:products
quantity:integer
mix ecto.migrate
Web/Modelle/invoice.ex
defmodule MyApp.Invoice do
use MyApp.Web, :model
schema "invoices" do
field :number, :string
has_many :line_items, MyApp.LineItem
[...]
web/Controller/invoice_controller.ex
[...]
def show(conn, %{"id" => id}) do
invoice =
Repo.get!(Invoice, id)
|> Repo.preload([:line_items])
render(conn, "show.html", invoice: invoice)
end
[...]
web/templates/Rechnung/show.html.eex
<h2>Invoice <%= @invoice.number %></h2>
<table class="table">
<thead>
<tr>
<th>Product</th>
<th>Quantity</th>
<th></th>
</tr>
</thead>
<tbody>
<%= for line_item <- @invoice.line_items do %>
<tr>
<td><%= line_item.product.name %></td>
<td><%= line_item.quantity %></td>
</tr>
<% end %>
</tbody>
</table>