title: How to use Ecto's has_many and cast_assoc
body: <p>I'm new to Elixir and Ecto and I would need some help with Ecto's has_many and cast_assoc. Can't understand the basics, like how am I to create a new model with assoc one.</p>
  
  <p>Here's my Has_Model:</p>
  
  <pre><code>defmodule Example.Has_Model do
    use Ecto.Schema
    import Ecto.Changeset
    alias Example.Repo
    alias Example.Has_Model
  
    schema "has_models" do
      has_many :belong_models, Example.Belong_Model
      field :name, string
      timestamps
    end
  
    def changeset(has_model, params \\ %{}) do
      has_model
      |&gt; cast(params, [:name])
    end
  end
  </code></pre>
  
  <p>and here's Belong_Model:</p>
  
  <pre><code>defmodule Example.Belong_Model do
    use Ecto.Schema
    import Ecto.Changeset
    alias Example.Repo
    alias Example.Belong_Model
  
    schema "belong_models" do
      belongs_to :has_model, Example.Has_Model
      field :name, string
      timestamps
    end
  
    def changeset(belong_model, params \\ %{}) do
      belong_model
      |&gt; cast(params, [:name])
      |&gt; cast_assoc(:has_model, required: true)
    end
  end
  </code></pre>
  
  <p><strong>Now, what I try to do is first to create a Has_Model</strong></p>
  
  <pre><code>iex()&gt; changeset = Example.Has_Model.changeset(%Has_Model, %{name: "I have"})
  iex()&gt; Example.Repo.insert(changeset)
  </code></pre>
  
  <p>This work ok.</p>
  
  <p><strong>Then I'd like to create a new Belong_Model and use that previously created Has_Model with it:</strong></p>
  
  <pre><code>iex()&gt; has = Example.Has_Model |&gt; Example.Repo.get_by(name: "I have")
  iex()&gt; changeset = Example.Belong_Model.changeset(%Belong_Model, %{name: "I belong", belongs_to: has})
  </code></pre>
  
  <p><strong>And this is where it fails:</strong></p>
  
  <pre><code>** (Ecto.CastError) expected params to be a map, got: `%Example.Has_Model{__meta__: #Ecto.Schema.Metadata&lt;:loaded, "has_models"&gt;, id: 1, inserted_at: #Ecto.DateTime&lt;2016-10-04 19:39:38&gt;, name: "I have", updated_at: #Ecto.DateTime&lt;2016-10-04 19:39:38&gt;, belong_models: #Ecto.Association.NotLoaded&lt;association :belong_models is not loaded&gt;}`
      (ecto) lib/ecto/changeset.ex:345: Ecto.Changeset.do_cast/4
      (example) lib/example/models/has_model.ex:15: Example.Has_Model.changeset/2
      (ecto) lib/ecto/changeset/relation.ex:99: Ecto.Changeset.Relation.do_cast/5
      (ecto) lib/ecto/changeset/relation.ex:235: Ecto.Changeset.Relation.single_change/5
      (ecto) lib/ecto/changeset.ex:571: Ecto.Changeset.cast_relation/4
      (example) lib/example/models/belong_model.ex:16: Example.Belong_Model.changeset/2
  </code></pre>
  
  <p>What's happening and what's the solution? I've tried to turn these parameters around the whole day but I just don't get it.</p>