title: Building and creating related objects via the association: how to set the foreign key of a nested model?
body: <p>I am using Ruby on Rails 3.1.0. I am trying to save a nested model having an attribute that is intended to store the foreign key of the parent model. At the creation time of the parent model I would like to set that attribute value to the parent model <code>id</code> value.</p>
  
  <p>In my model I have:</p>
  
  <pre><code>class Article &lt; ActiveRecord::Base  
    has_many :article_category_relationships
    has_many :categories,
      :through =&gt; :article_category_relationships
  
    # Accept nested model attributes
    accepts_nested_attributes_for :articles_category_relationships
  end
  
  class Category &lt; ActiveRecord::Base
    has_many   :article_category_relationships
    has_many   :articles,
      :through =&gt; :article_category_relationships
  end
  
  # The join model:
  class ArticleCategoryRelationship &lt; ActiveRecord::Base
    # Table columns are:
    #   - article_id
    #   - category_id
    #   - user_id
    #   - ...
  
    belongs_to :category
    belongs_to :article
  end
  </code></pre>
  
  <p>In my view I have the following:</p>
  
  <pre><code>...
  
  &lt;% @current_user.article_categories.each do |article_category| %&gt;
    &lt;%= check_box_tag 'article[articles_category_relationships_attributes][][category_id]', article_category.id, false %&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>In my controller I have:</p>
  
  <pre><code>def create
    @article = Article.new(params[:article])
  
    ...
  end
  </code></pre>
  
  <p><em>In my case, the <code>article_id</code> (related to the <code>ArticleCategoryRelationship</code> nested model) should be set to the <code>@article.id</code> value after the <code>Article</code> creation and the problem is that the Ruby on Rails framework seems do not set that value at the creation time.</em> In few words, considering my case, <strong>I would like to attach the foreign key automatically</strong>.</p>
  
  <p>Just to know, the generated <code>params</code> when the form is submitted is:</p>
  
  <pre><code>"article"=&gt;{"title"=&gt;"Sample title", "articles_category_relationships_attributes"=&gt;[{"category_id"=&gt;"8"}, {"category_id"=&gt;"9"}, {"category_id"=&gt;"10"}] }
  </code></pre>
  
  <p><strong>Is it possible to "auto"-set the foreign key</strong> (<code>article_id</code>) <strong>of the nested model? If so, how can I do that?</strong></p>