Repo 如何计算出 table 的名称?
How does the Repo figure out the name of the table?
我有更多菜鸟问题。当我做类似
的事情时
case MyRepo.insert %Post{title: "Ecto is great"} do
{:ok, struct} -> # Inserted with success
{:error, changeset} -> # Something went wrong
end
Repo 如何知道要使用数据库中的哪个 table?
Ecto 在调用 use Ecto.Schema
和 schema do ... end
的模块上定义了一个 __schema__
函数。如果您将 :source
传递给它,您将返回 table 名称。
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。
我有更多菜鸟问题。当我做类似
的事情时case MyRepo.insert %Post{title: "Ecto is great"} do
{:ok, struct} -> # Inserted with success
{:error, changeset} -> # Something went wrong
end
Repo 如何知道要使用数据库中的哪个 table?
Ecto 在调用 use Ecto.Schema
和 schema do ... end
的模块上定义了一个 __schema__
函数。如果您将 :source
传递给它,您将返回 table 名称。
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。