Created
October 15, 2019 21:41
-
-
Save nietaki/3827c17a2ea7693ae09f310ae4986d36 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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