Rails服务器在单击添加到购物车时说回滚转码

时间:2017-10-25 15:02:47

标签: ruby-on-rails ruby ruby-on-rails-3

刚刚开始在rails上学习ruby,我创建了一个简单的购物车应用程序但是当我点击“添加到购物车”时,我从我的服务器获得了一个回滚事务。我相信错误与我的orderitem控制器有关,但不知道如何在我的代码中解决这个问题。

rails服务器

Started POST "/order_items" for 127.0.0.1 at 2017-10-25 10:47:44 -0400
Processing by OrderItemsController#create as JS
  Parameters: {"utf8"=>"✓", "order_item"=>{"product_id"=>"13", "quantity"=>"1"}, "commit"=>"Add to cart"}
   (0.0ms)  begin transaction
  Product Load (0.5ms)  SELECT  "products".* FROM "products" WHERE "products"."id" = ? LIMIT ?  [["id", 13], ["LIMIT", 1]]
   (0.0ms)  rollback transaction
  Rendering order_items/create.js.erb
  Rendered order_items/create.js.erb (0.5ms)
Completed 200 OK in 1028ms (Views: 605.5ms | ActiveRecord: 0.5ms)

order_items_controller.rb

class OrderItemsController < ApplicationController

    def create
        @order = current_order
        @order_item = @order.order_items.new(order_item_params)
        @order.save
        session[:order_id] = @order.id
    end

    def update
        @order = current_order
        @order_item = @order.order_items.new(order_item_params)
        @order_item.update_attributes(order_item_params)
        @order_items = @order.order_items
    end

    def destroy
        @order = current_order
        @order_item = @order.order_items.find(params[:id])
        @order_item.destroy
        @order_items = @order.order_items
    end


    private

    def order_item_params
        params.require(:order_item).permit(:product_id, :quantity)
    end

end

create.js.erb

<% if @order.errors.any? || @order_item.errors.any? %>
    alert("Invalid")
<% else %>
    $(".cart").html("<%= escape_javascript(render 'layouts/cart') %>")
<% end %>

schema.rb

ActiveRecord::Schema.define(version: 20171019015705) do

  create_table "order_items", force: :cascade do |t|
    t.integer  "product_id"
    t.integer  "order_id"
    t.integer  "quantity"
    t.float    "total_price"
    t.float    "unit_price"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

  create_table "orders", force: :cascade do |t|
    t.float    "subtotal"
    t.float    "total"
    t.float    "shipping"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer  "user_id"
  end

  create_table "products", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.float    "price"
    t.text     "description"
    t.string   "picture"
  end

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.string   "username"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end

end

orderItem.rb

class OrderItem < ApplicationRecord
    belongs_to :order
    belongs_to :product

    before_save :set_unit_price
    before_save :set_total_price

    def unit_price
        if persisted?
            self[:unit_price]
        else
            product.price
        end
    end

    def total_price
        unit_price * quantity
    end

    private

    def set_unit_price
        self[:unit_price] = unit_price
    end

    def set_total_price
        self[:total_price] = quantity * set_unit_price
    end


end

order.rb

class Order < ApplicationRecord
    has_many :order_items
    belongs_to :user
    before_save :set_subtotal


    def subtotal
        order_items.collect {|order_item| order_item.valid? ? (order_item.unit_price*order_item.quantity) : 0}.sum
    end

    private

    def set_subtotal
        self[:subtotal] = subtotal
    end
end

user.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
    has_many :orders
 def to_param
        username
    end
end

carts_controller.rb

class CartsController < ApplicationController
  before_action :authenticate_user!

    def show
        @order_items = current_order.order_items
    end

end

Rails服务器现在

Started GET "/products" for 127.0.0.1 at 2017-10-25 11:21:11 -0400
Processing by ProductsController#index as HTML
  Rendering products/index.html.erb within layouts/application
  Product Load (0.0ms)  SELECT "products".* FROM "products"
  Rendered products/index.html.erb within layouts/application (16.0ms)
  User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 1], ["LIMIT", 1]]
  Rendered layouts/_cart.html.erb (1.0ms)
  Rendered layouts/_nav.html.erb (34.3ms)
Completed 200 OK in 604ms (Views: 571.1ms | ActiveRecord: 0.5ms)

1 个答案:

答案 0 :(得分:0)

@order_item = @order.order_items.new(order_item_params)

仅在内存中创建项目。这没有什么不对。但我认为你需要改变新的创建如此

@order_item = @order.order_items.create(order_item_params)