Last week I used Ecto models to quickly created the database and I was very surprised how all got generated for me. But the model I build was very simplistic, and now I need to extend it. I started working on first serious functionality for the project, and I’ll have to do some changes. For start, I’m just testing by adding one field.
I generated new migrations file in /priv/repo/migrations
folder and a bit by trial and error I end up with file like that:
defmodule Flightlog.Repo.Migrations.CreateFlight do use Ecto.Migration def change do alter table(:flights) do add :plane_type, :string end end end
And after running mix ecto.migrate
, I actually got some results:
Michals-MBP:flightlog michal$ mix ecto.migrate 01:01:37.663 [info] == Running Flightlog.Repo.Migrations.CreateFlight.change/0 forward 01:01:37.663 [info] alter table flights 01:01:37.666 [info] == Migrated in 0.0s
This worked for adding fields to the database but didn’t automagically update all the access layers. There’s probably some way to it, but this time I did it manually.
First I updated the views, for example added following into show.html.eex
:
https://gist.github.com/mlusiak/0979cb46187ee75cd724190e09aa96c1
This solved the visuals but still didn’t work. The crucial were changes in the model:
defmodule Flightlog.Flight do use Flightlog.Web, :model schema "flights" do field :date, Ecto.DateTime field :flight_number, :string field :plane_type, :string field :from, :string field :to, :string timestamps() end @doc """ Builds a changeset based on the `struct` and `params`. """ def changeset(struct, params \\ %{}) do struct |> cast(params, [:date, :flight_number, :plane_type, :from, :to]) |> validate_required([:date, :flight_number, :plane_type, :from, :to]) end end
I added new field both in schema part and in changeset. Cast
is responsible for things being updated. I didn’t have to add it to be validates as required.
So this was actually a bit tedious, but I’m probably missing something here. Hopefully I’ll figure it out by the time I’ll need to make bigger changes.
I also found this post, that’s deal with similar problem.
That’s all for today. Tune in next week for another part. Also, check previous episodes. And if you’re interested in machine learning, look into my weekly link drop.
2 thoughts on “Extending your Ecto model”