title: How to deal with error "Couldn't find Model with id=0"
body: <p>Abstracting from my actual database, I have Model1 and Model2 and Model1 has_and_belongs_to_many Model2 and Model2 has_and_belongs_to_many Model1.  In a sign-up page, I have the following:</p>
  
  <pre><code>= f.hidden_field :model2_ids
  </code></pre>
  
  <p>But when doing a sign-up where there is no existing model2's in the database, I get the following error:</p>
  
  <pre><code>"Couldn't find Model2 with id=0"
  </code></pre>
  
  <p>In the params you can see:</p>
  
  <pre><code>"model2_ids"=&gt;"[]",
  </code></pre>
  
  <p>I suppose this evaluates to NULL, which is why I am getting the error I am.  How can I get around this?</p>
  
  <p>Update:</p>
  
  <p>By setting a conditional in the view, I can avoid this problem with a signup where there is no existing model2's or otherwise is no model2_ids being set.  The model2_ids are being set in the controller through an invitation model, and in some signup cases there is an invitation, where the invitation model is specifying a model2.  In an example case, I see in the params:</p>
  
  <pre><code> "model2_ids"=&gt;"[1]",
  </code></pre>
  
  <p>However, I get the same error and this output from the server logs:</p>
  
  <pre><code>  Invitation Load (1.2ms)  SELECT "invitations".* FROM "invitations" WHERE "invitations"."token" = '80c98940448829e7edc623f9886e6930434e245c' LIMIT 1
    Model2 Load (51.8ms)  SELECT "model2s".* FROM "model2s" WHERE "model2s"."id" = $1 LIMIT 1  [["id", 0]]
  Completed 404 Not Found in 222ms
  
  ActiveRecord::RecordNotFound (Couldn't find Listing with id=0):
    app/controllers/registrations_controller.rb:12:in `create'
  </code></pre>
  
  <p>What is causing this?</p>