title: Rails 4 - Convert id to model in params
body: <p>My code is errorring out when I try to insert a new record in the DB:</p>
  
  <pre><code>@user_request = UserRequest.new(user_request_params)
  </code></pre>
  
  <p>I have a model that belongs to another. The user selects the sub model in a dropdown, and the id is sent in json:</p>
  
  <pre><code>{"user_request"=&gt;{"product_ids"=&gt;["86", "79"], "sub_model_id"=&gt;"5"}
  </code></pre>
  
  <p><strong>Schema</strong></p>
  
  <pre><code>UserRequest
    has_and_belongs_to_many :products
    has_one :sub_model
  
  SubModel
    belongs_to :user_request
  
  Product
    has_and_belongs_to_many :user_requests
  </code></pre>
  
  <p>The product is inserted into the db no problem (if I ignore the submodel), but the SubModel is not. I get this error:</p>
  
  <pre><code>ActiveRecord::UnknownAttributeError (unknown attribute: sub_model_id):
    app/controllers/user_requests_controller.rb:44:in `create'
  </code></pre>
  
  <p>I tried to edit the params before hand by doing this:</p>
  
  <pre><code>def user_request_params
      params.require(:user_request).permit(:sub_model_id, :product_ids =&gt; [])
      #the above line was there, added these lines:
      sub_id = params[:user_request][:sub_model_id]
      sub = SubModel.find(sub_id)
      params[:user_request].delete(:sub_model_id)
      params[:user_request][:sub_model] = sub
      params
  end
  </code></pre>
  
  <p>which generates the following JSON:</p>
  
  <pre><code>{"user_request"=&gt;{"product_ids"=&gt;["86", "79"], "sub_model"=&gt;#&lt;SubModel id: 5, ...} 
  </code></pre>
  
  <p>but now I get this error:</p>
  
  <pre><code>ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError):
  </code></pre>
  
  <p>app/controllers/user_requests_controller.rb:42:in `create'</p>
  
  <p>The submodel's were generated before hand by the admin of the site (they do exist).</p>
  
  <p><strong>How do I get the UserRequest to save?</strong></p>