Skip to content

Instantly share code, notes, and snippets.

@nietaki
Created October 15, 2019 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nietaki/3827c17a2ea7693ae09f310ae4986d36 to your computer and use it in GitHub Desktop.
Save nietaki/3827c17a2ea7693ae09f310ae4986d36 to your computer and use it in GitHub Desktop.
defmodule BlogExample.Schema.PostWithVirtualCategory do
use Ecto.Schema
schema "posts" do
field(:title, :string, null: false)
field(:contents, :string, null: false)
field(:category_name, :string)
field(:category, :map, virtual: true)
belongs_to(:user, BlogExample.Schema.User)
end
def populate_category(%__MODULE__{category_name: nil} = post) do
post
end
def populate_category(%__MODULE__{category_name: category_name} = post) do
category = BlogExample.RemoteService.retrieve_category_info(category_name)
%__MODULE__{post | category: category}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment