title: Nested model form with mutliple has_many/belongs_to associations
body: <p>I have three models:</p>
  
  <pre><code>class Rate &lt; ActiveRecord::Base
    attr_accessible :user_id, :car_id, :rate
  
    belongs_to :user
    belongs_to :car
  end
  
  class User &lt; ActiveRecord::Base
    attr_accessible :name
  
    has_many :rates
    accepts_nested_attributes_for :rates
  end
  
  class Car &lt; ActiveRecord::Base
    attr_accessible :name
  
    has_many :rates
    accepts_nested_attributes_for :rates
  end
  </code></pre>
  
  <p>And one controller:</p>
  
  <pre><code>class UsersController &lt; ResourceController
    def new
      # Assume user is loaded
      @user.rates.build
    end
  end
  </code></pre>
  
  <p>I'm trying to build a nested form that will associate a list of users/cars and their associated rates.</p>
  
  <p>Something like:</p>
  
  <pre><code>&lt;% form_for @user do |f| %&gt;
    &lt;%= @user.name %&gt;&lt;br /&gt;
    &lt;% Car.all.each do |car| %&gt;
      &lt;%= car.name %&gt;&lt;br /&gt;
      &lt;%= f.fields_for :rates do |r| %&gt;
        &lt;%= r.number_field :rate %&gt;
      &lt;% end %&gt;
    &lt;% end %&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>The problem is that I would like the Rate model to store data as follows:</p>
  
  <pre><code>USER_ID    CAR_ID    RATE
  1          1         10
  1          2         20
  1          3         30
  2          1         40
  3          2         50
  </code></pre>
  
  <p>I cannot figure out how to properly build the <code>fields_for</code> helper to build the proper params for both the <code>user_id</code> and the <code>car_id</code>.</p>
  
  <p>Something like:</p>
  
  <pre><code>user[car=1][rate]
  user[car=2][rate]
  </code></pre>
  
  <p>I've tried being more explicit with the <code>fields_for</code> like this:</p>
  
  <pre><code>&lt;%= r.fields_for 'user[car][rate]' %&gt;
  </code></pre>
  
  <p>But it still doesn't build out the nested parameters properly. The car parameter is not correctly identified.</p>
  
  <p>Any help would be appreciated! Thanks.</p>
  
  <p>EDIT:
  The controller action has to be under user. The example above has been shortened for brevity but other user-related attributes are available through the form so it has to use the users controller.</p>
  
  <p>ANSWER:
  I figured out a way to do it. I've <a href="https://stackoverflow.com/a/15143990/403664">added my own answer</a> that explains it.</p>