I have a self-referenced (parent
/children
) model in my app.
I know I could describe relationships this way:
belongs_to(:parent, Model)
has_many(:children, Model, foreign_key: :parent_id)
But in my case, the model has a code
attribute.
Children Model
s code
look like A10101
, while parents look like A10
.
Can I describe those relationship without having to create an extra parent_id
column, using something like a dynamic foreign key?
I could write the methods:
def parent(model) do
parent_code = String.slice(model.code, 0..2)
if length(parent_code) > 0 do
Repo.get_by(__MODULE__, code: parent_code)
end
end
def children(model) do
if Regex.match?(~r/[A-Z]\d\d/, model.code) do
Repo.all(from m in Model, where: like(m.code, "#{model.code}%"))
end
end
But having proper relationships would allow me to use things like Repo.preload
which would be neat.
Thanks