Skip to content

Instantly share code, notes, and snippets.

@niku
Created April 30, 2015 12:38
Show Gist options
  • Save niku/4b724eef797bc714bb91 to your computer and use it in GitHub Desktop.
Save niku/4b724eef797bc714bb91 to your computer and use it in GitHub Desktop.

I'd like to use PostgreSQL's Inheritance on Ecto. http://www.postgresql.org/docs/9.4/static/ddl-inherit.html

For example, I want to use following like:

defmodule Repo.CreateCities do
  use Ecto.Migration

  def up do
    create table(:cities) do
      add :name,        :string
      add :populateion, :float
      add :altitude,    :integer
      timestamps
    end

    # A table can inherit from more than one parent table
    create table(:capitals, inherits: [:cities]) do
      add :state, :string,
    end
  end

  def down do
    drop table(:capitals)
    drop table(:city)
  end
end

defmodule City do
  use Ecto.Model

  schema "cities" do
    field :name,        :string
    field :populateion, :float
    field :altitude,    :integer

    timestamps
  end
end

defmodule Capital do
  use Ecto.Model

  schema "capitals" do
    inherit_from :city
    field :state, :string
  end
end

InheritsSample.Repo.all(City)
# => [
#   %City{__meta__: %Ecto.Schema.Metadata{source: "cities", state: :loaded}, name: "Las Vegas", ...},
#   %City{__meta__: %Ecto.Schema.Metadata{source: "cities", state: :loaded}, name: "Mariposa", ...},
#   %Capital{__meta__: %Ecto.Schema.Metadata{source: "capitals", state: :loaded}, name: "Madison", ...}
# ]

Any plans for inheritance? or Any Suggestions?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment