I currently have a "Rank" model which contains the field (integer) "rank" which is an integer. The "Ship" model on the other hand has a "usable_by" field (integer). What I want to achieve is that when I return a Rank they also contain a list of all Ship models where the "usable_by" field matches the "rank" field in the Rank model. I know this is doable by a query and populating the data manually I guess, but is there anything built into Ecto/Phoenix I can use to make this easier?
I guess the ideal situation I am hoping for is using has_many (I don't really care about the reverse association) with something like :references, or foregin_key, but I can't seem to get it to work. This is the line i am currently using:
Rank model
schema "ranks" do
field :name, :string
field :rank, :integer
timestamps
has_many :ships, Playground.Ship #Can I use :foregin_key and :references here?
end
I guess you've found your answer by now, but if someone else stumbles on this post the answer is this :
has_many :ships, Playground.Ship, foreign_key: :usable_by
This way you can use a custom field name on your associated model.
You should use references in your migration (where you'll actually update the database). Here the Playground.Ship
acts like a reference to a certain model, :created_by
is the name that will be used in the relationship association.