Hello, I have seen quite a few mentions of @foreign_key_type combined with e.g. a string primary key, but I can’t really understand its working and can’t find any docs about it?
As far as I can tell it applies wholesale to all foreign keys in the schema where the directive is defined, rather than where said schema itself is used as a foreign relation. I hope I made myself clear (see below), but if is the case, this makes no sense to me. What did I miss?
Example:
defmodule Book do
....
@primary_key {:id, :string, autogenerate: false}
@foreign_key_type :string
schema "books" do
belongs_to :author, Author # now :author_id is expected to be string?
end
end
defmodule Page do
....
schema "pages" do
belongs_to :book, Book # I would expect :book_id to be of type string now
end
end
You would also need to set the @foreign_key_type (as well as @primary_key_type) in your Page module since you are not using the default key type of :id
Thanks, but if you read you right this implies the entire database uses the same type of primary key, which is not the case for me. The example is fictitious, but imagine the Book schema has an ISBN string as pk, while Page uses normal integers.
I must conclude the @foreign_key_type directive is only useful when the entire database uses a non-standard pk type.
Great, thanks for clearing that up. BTW, the reason I complained about the docs is when I type foreign_key in the hexdocs search box it never shows the page this directive is described on? I think it would be more useful if it were a proper full text search.