2016-06-02 4 views
1

У меня есть 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> 

ответ

1

Один из способов справиться с этим делом, чтобы добавить Ecto.Schema.has_many/3:through вариант, как так:

веб/модели/invoice.ex

defmodule MyApp.Invoice do 
    # ... 
    schema "invoices" do 
    field :number, :string 
    has_many :line_items, HasMany.LineItem 
    has_many :products, through: [:line_items, :product] 

    timestamps 
    end 
    # ... 
end 

Поскольку ассоциация проходит через :line_items, вы поджать как связаны :line_items и :products с запросом, как это:

Сети/Контроллеры/invoice_controller.ex

def show(conn, %{"id" => id}) do 
    invoice = 
    Repo.get!(Invoice, id) 
    |> Repo.preload([:products]) 

    render(conn, "show.html", invoice: invoice) 
end 

Документы обеспечивают некоторые большие примеры в отношении "has_many/has_one: через" ассоциацию: https://hexdocs.pm/ecto/Ecto.Schema.html#has_many/3

Смежные вопросы