得到了Fixnum:Rails回滚错误

时间:2015-09-09 10:34:32

标签: ruby-on-rails

你好我正在使用rails上的ruby进行迁移:

 class CombineItemsInCart < ActiveRecord::Migration
    def up
        Cart.all.each do |cart|
            sums = cart.line_items.group(:product_id).sum(:quantity)

            sums.each do |product_id, quantity|
                cart.line_items.where(product_id: product_id).delete_all

                item = cart.line_items.build(product_id: product_id)
                item.quantity = quantity
                item.save!
            end
        end
    end

    def down
        LineItem.where("quantity>1").each do |line_item|
            line_item.quantity.times do 
                LineItem.create cart_id: line_item.cart_id,
                product: line_item.product_id, quantity: 1
            end
            line_item.destroy
        end
    end

end

当我在我的控制台中输入回滚命令时,我发现了这个错误:

Product(#58221600) expected, got Fixnum(#17692120)/var/lib/gems/2.1.0/gems/activerecord-4.2.4/lib/active_record/associations/association.rb:218:in `raise_on_type_mismatch!

为什么说我要分配一个fixnum? 感谢所有的帮助

1 个答案:

答案 0 :(得分:1)

您的product: line_item.product_id应为产品:line_item.product

def down
    LineItem.where("quantity>1").each do |line_item|
        line_item.quantity.times do 
            LineItem.create cart_id: line_item.cart_id,
            product: line_item.product, quantity: 1
        end
        line_item.destroy
    end
end

或者您也可以这样做:

def down
    LineItem.where("quantity>1").each do |line_item|
        line_item.quantity.times do 
            LineItem.create cart_id: line_item.cart_id,
            product_id: line_item.product_id, quantity: 1
        end
        line_item.destroy
    end
end