Skip to main content

Posts

Showing posts with the label Ecto

Ecto "inheritance" using macros

Oooh them's fighting words. Anyways, this is definitely not true inheritance by any means, but let me explain the problem and then the solution. Ecto is the primary way you connect to the database in Phoenix. However, Ecto differs in many significant ways from ActiveRecord in Rails. You can set up a schema file which lists the relationships between your "models" or "entities", but these schemas do not allow you to directly access the database. They are merely descriptions of how the data is expressed. To access the database, you need to use a data context which uses Ecto. So, from my article comparing Active Record to Ecto ( http://www.skuunk.com/2020/01/comparing-rails-active-record-pattern.html ) defmodule Schema.Article do use Ecto.Schema import Ecto.Changeset alias Schema.Author alias Schema.Comment @permitted_fields [:title, :content] @required_fields [:title, :content] schema "article" do belongs_to(:author, Author) ...

Comparing Rails' Active Record Pattern with Phoenix/Elixir/Ecto

Rails has a very well established Active Record pattern for dealing with the database. You have an Active Record model which maps to the database table, the schema of the model comes directly from the database schema and you place your model specific methods on the Active Record model. This file is also where you set your model relationships (e.g. has_many, has_one, belongs_to). Your instance of the model has all the methods built in. In Ecto/Phoenix it's a little different. First of all, the database schema doesn't automatically map to the "model". In fact we don't really have models (as Elixir is a functional paradigm). What happens in one file in Rails, happens in essentially two (or more). You have a schema file (where you have to list out all the attributes and relationships). Using the schema file, your "instance" is essentially a data structure (with no methods on it). If you want to transform the data on your struct, you would use a context mod...