How to insert rows in a many-to-many relationship

Posted by GSound on Stack Overflow See other posts from Stack Overflow or by GSound
Published on 2010-05-28T16:11:27Z Indexed on 2010/05/28 16:32 UTC
Read the original article Hit count: 144

Filed under:
|
|
|

Hello,

I am having an issue trying to save into an intermediate table. I am new on Rails and I have spent a couple of hours on this but can't make it work, maybe I am doing wrong the whole thing. Any help will be appreciated. =)

The app is a simple book store, where a logged-in user picks books and then create an order.

This error is displayed:

NameError in OrderController#create
uninitialized constant Order::Orderlist


These are my models:

class Book < ActiveRecord::Base  
    has_many :orderlists
    has_many :orders, :through => :orderlists
end

class Order < ActiveRecord::Base
    belongs_to :user
    has_many :orderlists
    has_many :books, :through => :orderlists
end

class OrderList < ActiveRecord::Base
    belongs_to :book
    belongs_to :order
end


This is my Order controller:

class OrderController < ApplicationController

    def add
        if session[:user]
            book = Book.find(:first, :conditions => ["id = #{params[:id]}"])
            if book
                session[:list].push(book)
            end
            redirect_to :controller => "book"
        else
            redirect_to :controller => "user"
        end
     end

    def create
        if session[:user]
            @order = Order.new
            if @order.save
                session[:list].each do |b|
                    @order.orderlists.create(:book => b) # <-- here is my prob I cant make it work
                end
            end
        end
        redirect_to :controller => "book"
    end
end

Thnx in advance!
Manuel

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby