views:

60

answers:

3

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

+2  A: 

Only got time to look at this briefly, I'm afraid, but the first thing I spot is that your has_many relations are called :orderlists. I think that needs to be :order_lists, with an underscore.

Chris
I think Chris is right here. The convention is that CamelCased words become :camel_cased when turned into a symbol.
Stephen Orr
A: 

Yes that was one of the problems. Then I could make it work with this line in the 'create' method:

def create
    if session[:user]
        @order = Order.new
        if @order.save
            session[:list].each do |b|
                OrderList.create(:book => b, :order => @order)
            end
        end
    end
    redirect_to :controller => "book"
end

Thanks Chris

GSound
+1  A: 

This is not directly associated with your question but this query:

book = Book.find(:first, :conditions => ["id = #{params[:id]}"])

...is vulnerable to sql injection. In this case content of params[:id] gets passed to sql without proper escaping. I would suggest changing this line to something like this:

book = Book.find(:first, :conditions => ["id = ?, params[:id]])

Here's explanation: http://wiki.rubyonrails.org/howtos/security/sql_injection

Uģis Ozols
Thnx Uģis. Good to know! :D
GSound