title: How do I define Elixir Ecto schema for a has_one / belongs_to_many association?
body: <p>In the explanation of the Belongs To/Has One association at <a href="https://elixirschool.com/en/lessons/ecto/associations/#belongs-tohas-one" rel="nofollow noreferrer">https://elixirschool.com/en/lessons/ecto/associations/#belongs-tohas-one</a> the author writes:</p>
  
  <blockquote>
    <p>Let’s say that a movie has one distributor, for example Netflix is the
    distributor of their original film “Bright”.</p>
    
    <p>...</p>
    
    <p>...the Distributor schema should use the belongs_to/3 macro to allow
    us to call distributor.movie and look up a distributor’s associated
    movie using this foreign key.</p>
    
    <p>...</p>
    
    <p>The has_one/3 macro functions just like the has_many/3 macro. It uses
    the associated schema’s foreign key to look up and expose the movie’s
    distributor. This will allow us to call movie.distributor.</p>
  </blockquote>
  
  <p>Here are the schemas for their example:</p>
  
  
  
  <pre class="lang-rb prettyprint-override"><code>defmodule Example.Distributor do
    use Ecto.Schema
  
    schema "distributors" do
      field :name, :string
      belongs_to :movie, Example.Movie
    end
  end
  
  defmodule Example.Movie do
    use Ecto.Schema
  
    schema "movies" do
      field :title, :string
      field :tagline, :string
      has_many :characters, Example.Character
      has_one :distributor, Example.Distributor # I'm new!
    end
  end
  </code></pre>
  
  <p><a href="https://stackoverflow.com/users/588267/jos%C3%A9-valim">José Valim</a> writes in <a href="http://blog.plataformatec.com.br/2015/08/working-with-ecto-associations-and-embeds/" rel="nofollow noreferrer">http://blog.plataformatec.com.br/2015/08/working-with-ecto-associations-and-embeds/</a>:</p>
  
  <blockquote>
    <p>The difference between has_one/3 and belongs_to/3 is that the foreign
    key is always defined in the schema that invokes belongs_to/3.</p>
  </blockquote>
  
  <p>So by using belongs_to/3 in the Distributor schema, a foreign key is defined in that schema, limiting a single distributor in this example to a single movie. (This is confirmed by the example writer's "...to allow us to call distributor.movie and look up a distributor’s associated movie using this foreign key.")</p>
  
  <p>How would I define the schema if I want a movie to have one distributor, but a single distributor to have one <strong>or more</strong> movies?</p>