У меня есть invoice
который has_many line_items
который принадлежит_от products
тоже. На invoice#show
Я хочу показать все line_items
этого invoice
с name
связанных product
. Исходя из Rails, мне сложно связать точки. line_item.product.name
в шаблоне не работает. Как я могу отобразить имя продукта в этой таблице?Показать атрибуты has_many через соединение
Применение
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
веб/модели/invoice.ex
defmodule MyApp.Invoice do
use MyApp.Web, :model
schema "invoices" do
field :number, :string
has_many :line_items, MyApp.LineItem
[...]
веб/контроллеры/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
[...]
веб/шаблоны/счета/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>