开发者

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

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


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜