Hi everyone, having some trouble understanding how to model a particular problem with Ecto. I just finished reading the first part of Programming Ecto, and skimmed a few chapters of the second part looking for relevant info but came up short. Ditto for the Ecto docs and the cheatsheet, which is really good, but still can’t figure out the answer myself.
I’ve got the following initial migration (a port of another project of mine in another language):
defmodule Repo.Migrations.Genesis do
use Ecto.Migration
def change do
create table("persons") do
add :code, :string, null: false
add :name, :string, null: false
timestamps()
end
create unique_index("persons", [:code])
create table("expenses") do
add :date, :date, null: false
add :description, :string, null: false
timestamps()
end
create table("persons_expenses") do
add :person_id, references("persons"), null: false
add :expense_id, references("persons"), null: false
add :amount, :decimal, null: false
timestamps()
end
create unique_index("persons_expenses", [:person_id, :expense_id])
end
end
Now in terms of schemas, I’m unsure of what to do. In the Person
schema I’d like to have the list of its corresponding expenses+amount; and in the Expense
schema I’d like to have the list of its corresponding persons+amount.
defmodule Person do
use Ecto.Schema
schema "persons" do
field :code, :string
field :name, :string
timestamps()
has_many :expenses, Expense # though: [...] maybe?
end
end
defmodule Expense do
use Ecto.Schema
schema "expense" do
field :date, :date
field :description, :string
timestamps()
has_many :person_expense, PersonExpense
end
end
defmodule PersonExpense do
use Ecto.Schema
schema "person_expense" do
field :amount, :decimal
timestamps()
belongs_to :person, Person
belongs_to :expense, Expense
end
end
Is the above the best I can do? It somehow doesn’t feel right. How you model this instead? Any help greatly appreciated!