title: Shopping Cart has_many through association
body: <p>I am trying to create a very simple shopping cart example using the has_many through association.</p>
  
  <p>I have a cart model:</p>
  
  <pre><code>class Cart &lt; ActiveRecord::Base
    has_many :cart_products
    has_many :products, :through =&gt; :cart_products
  end
  </code></pre>
  
  <p>A cart_products model:</p>
  
  <pre><code>class CartProduct &lt; ActiveRecord::Base
    belongs_to :cart
    belongs_to :product
  end
  </code></pre>
  
  <p>And a products model:</p>
  
  <pre><code>class Product &lt; ActiveRecord::Base
    has_many :cart_products
    has_many :carts, :through =&gt; :cart_products
  end
  </code></pre>
  
  <p>I have a cart controller that has a add function:</p>
  
  <pre><code>  def add
      @product = Product.find(params[:product_id])
  
      if request.xhr?
        @cart_product = @cart.add(params[:id])
        render :action =&gt; "add"
      else
        render
      end
    end
  </code></pre>
  
  <p>And in the routes config file:</p>
  
  <pre><code>  resources :cart do
      post 'add'
    end
  </code></pre>
  
  <p>In the applications controller, I have an function to initialise the cart:</p>
  
  <pre><code>  def initialse_cart
      @cart = Cart.find(session[:cart_id])
      rescue ActiveRecord::RecordNotFound
      @cart = Cart.create
      session[:cart_id] = @cart.id
    end
  </code></pre>
  
  <p>What I am unsure about is how do I pass the cart ID in the products controller?</p>
  
  <p>I know you can do @cart.products. But how do you do the other way around?</p>
  
  <p>Thanks.</p>