Get model from a table

I learned that if we have a model name then we can use that model to get the table lie this


It will return

 [Ecto.Schema.Metadata, nil, {nil, table_name}, :built]

My question is how can i do that in reverse?

Lets say i have a table name "jobs". How can i use this to get the model of this table?

There may be none, one or indeed many modules that define a struct representing a database table. But there’s no implied mapping between module name and table name and theres no place that a reverse mapping is maintained by Ecto. If thats what you need its up to you to maintain the mapping.

Note that in your example of model_name.__struct__.__meta__, the model_name is just a struct reference. So %SomeModule{}.__struct__ just returns SomeModule. __struct__ is just a member of the struct that stores the name of the module that it represents.

__meta__ is just a function on the module that returns the meta data created by Ecto at compilation time.

I did at one time think I needed a reverse mapping from table name to Ecto module. I did all sorts of compile time contortion to invoke __meta__ on all known modules and create a new module that maintained the reverse mapping. It was a pain. Not very maintainable. And since there may well be a 1:n mapping of tables to Ecto modules it wasn’t that helpful.

1 Like

First, it’s better to say An Ecto schema than a model.

Then schema works like that:

  schema "table_name" do


So with our old friend grep :tiger::

grep -i -r 'schema "jobs" do' lib/my_app/*

1 Like

Thanks that explains a lot.