2016-09-23 26 views
0

我有更多的noob問題。當我做類似回購如何找出表的名字?

case MyRepo.insert %Post{title: "Ecto is great"} do 
    {:ok, struct}  -> # Inserted with success 
    {:error, changeset} -> # Something went wrong 
end 

回購如何知道數據庫中的哪個表使用?

回答

3

Ecto在模塊上定義了一個__schema__函數,該函數調用use Ecto.Schema,然後調用schema do ... end。如果您將:source傳遞給它,您將返回表名稱。

iex(1)> %MyApp.Post{} 
%MyApp.Post{__meta__: #Ecto.Schema.Metadata<:built, "posts">, 
comments: #Ecto.Association.NotLoaded<association :comments is not loaded>, 
id: nil, inserted_at: nil, title: nil, updated_at: nil} 
iex(2)> %MyApp.Post{}.__struct__ 
MyApp.Post 
iex(3)> %MyApp.Post{}.__struct__.__schema__(:source) 
"posts" 

__schema__接受的各種參數進行了說明here

+0

太棒了!所以這意味着表名最終來自模式的名稱,對吧? – dotslash

+1

是的,模式的第一個參數是「源」或表名。 – Dogbert