Rails电子商务应用程序中的RecordNotFound错误

时间:2018-09-26 08:31:25

标签: ruby-on-rails

我正在用栏杆构建一个电子商务应用程序,其中有两个产品Chairs和Bookcabinets,我已经为椅子和Bookcabinets创建了两个不同的控制器和模型,现在都可以了,我希望用户能够将这些产品添加到购物车中因此,我通过观看教程从头开始创建了一个订购系统,该系统适用于椅子,但是当我将书柜添加到shopping_cart模型中时,出现了错误:Couldn't find Chair with 'id'=

服务器日志

Started POST "/cart/items" for 127.0.0.1 at 2018-09-26 14:16:43 +0530
   (0.7ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
Processing by OrderItemsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"wGAl7gZGXipKt7EzzZT1LuBgn2k8KnlaPagp0cQ3l6pIkr6mx8MdJAuhgkY7EEttrHjTSSpcRjqe0qZ0a2hrAA==", "bookcabinet_id"=>"1", "quantity"=>"40"}
  Chair Load (0.8ms)  SELECT  "chairs".* FROM "chairs" WHERE "chairs"."id" = ? LIMIT ?  [["id", nil], ["LIMIT", 1]]
Completed 404 Not Found in 106ms (ActiveRecord: 3.8ms)



ActiveRecord::RecordNotFound (Couldn't find Chair with 'id'=):

app/models/shopping_cart.rb:20:in `add_item'
app/controllers/order_items_controller.rb:8:in `create'

我的Order_items_controller

class OrderItemsController < ApplicationController

  def index
    @items = current_cart.order.items
  end

  def create
    current_cart.add_item(
      chair_id: params[:chair_id],
      bookcabinet_id: params[:bookcabinet_id],
      quantity: params[:quantity]
    )

    redirect_to cart_path
  end

  def destroy
    current_cart.remove_item(id: params[:id])
    redirect_to cart_path
  end

end

我的Order_controller

class OrdersController < ApplicationController
    def new
        @order = current_cart.order
    end
end

**我的订单模型**

class Order < ApplicationRecord
    has_many :items, class_name: 'OrderItem'
end

我的Order_item模型

class OrderItem < ApplicationRecord
    belongs_to :order
    belongs_to :chair
    belongs_to :bookcabinet
end

我的购物车模型

class ShoppingCart

  delegate :sub_total, to: :order

  def initialize(token:)
    @token = token
  end

  def order
    @order ||= Order.find_or_create_by(token: @token) do |order|
      order.sub_total = 0
    end
  end

  def items_count
    order.items.sum(:quantity)
  end

  def add_item(chair_id:, bookcabinet_id:, quantity: 1)
    chair = Chair.find(chair_id),
    bookcabinet = Bookcabinet.find(bookcabinet_id)

    order_item = order.items.find_or_initialize_by(
      chair_id: chair_id,
      bookcabinet_id: bookcabinet_id
    )

    order_item.price = chair.price
    order_item.price = bookcabinet.price

    order_item.quantity = quantity

    ActiveRecord::Base.transaction do
      order_item.save
      update_sub_total!
    end
  end


  def remove_item(id:)
    ActiveRecord::Base.transaction do
      order.items.destroy(id)
      update_sub_total!
    end
  end

  private

  def update_sub_total!
    order.sub_total = order.items.sum('quantity*price')
    order.save
  end

end

我的Create_order迁移

class CreateOrders < ActiveRecord::Migration[5.1]
  def change
    create_table :orders do |t|
      t.string :first_name
      t.string :last_name, null: false
      t.decimal :sub_total, precision: 15, scale: 2, null: false

      t.timestamps
    end
  end
end

我的CreateOrderItems迁移

class CreateOrderItems < ActiveRecord::Migration[5.1]
  def change
    create_table :order_items do |t|
      t.belongs_to :order, null: false
      t.belongs_to :chair, null: false
      t.belongs_to :bookcabinet
      t.integer :quantity, null: false
      t.decimal :price, precision: 15, scale: 2, null: false

      t.timestamps
    end


  end
end

路线

  get '/cart', to: 'order_items#index'
  resources :order_items, path: '/cart/items'
  get '/cart/checkout', to: 'orders#new', as: :checkout
  patch '/cart/checkout', to: 'orders#create'

添加到购物车表单

<div class="button my-2">
              <%= form_tag order_items_path do %>
        <%= hidden_field_tag :bookcabinet_id, @bookcabinet.id %>
        <%= number_field_tag :quantity, 1 %>

        <button type="submit" class="btn cart"><i class="d-inline fa fa-cart-arrow-down" aria-hidden="true"></i><p class="d-inline">Add To Cart</p></button>
      <% end %>

更新的服务器日志

Started POST "/cart/items" for 127.0.0.1 at 2018-09-27 00:24:13 +0530
   (0.6ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
Processing by OrderItemsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"gqwsV8Z/0p74Y8WPLMmfk9vmoSPCFpP+lAtVxxH3KSvWUzYYIFtbQRkAzM5yh5HS/wAzelr90LJW64joFUpGwg==", "bookcabinet_id"=>"1", "quantity"=>"40"}
  Bookcabinet Load (0.7ms)  SELECT  "bookcabinets".* FROM "bookcabinets" WHERE "bookcabinets"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  Order Load (0.9ms)  SELECT  "orders".* FROM "orders" WHERE "orders"."token" = ? LIMIT ?  [["token", "20897ec5db2636f5"], ["LIMIT", 1]]
  OrderItem Load (0.5ms)  SELECT  "order_items".* FROM "order_items" WHERE "order_items"."order_id" = ? AND "order_items"."chair_id" IS NULL AND "order_items"."bookcabinet_id" = ? LIMIT ?  [["order_id", 4], ["bookcabinet_id", 1], ["LIMIT", 1]]
   (0.2ms)  begin transaction
  Bookcabinet Load (0.3ms)  SELECT  "bookcabinets".* FROM "bookcabinets" WHERE "bookcabinets"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
   (0.4ms)  SELECT SUM(quantity*price) FROM "order_items" WHERE "order_items"."order_id" = ?  [["order_id", 4]]
   (0.2ms)  commit transaction
Redirected to http://localhost:3000/cart
Completed 302 Found in 557ms (ActiveRecord: 10.4ms)


Started GET "/cart" for 127.0.0.1 at 2018-09-27 00:24:14 +0530
Processing by OrderItemsController#index as HTML
  Order Load (0.5ms)  SELECT  "orders".* FROM "orders" WHERE "orders"."token" = ? LIMIT ?  [["token", "20897ec5db2636f5"], ["LIMIT", 1]]
  Rendering order_items/index.html.erb within layouts/application
   (0.4ms)  SELECT SUM("order_items"."quantity") FROM "order_items" WHERE "order_items"."order_id" = ?  [["order_id", 4]]
  OrderItem Load (1.1ms)  SELECT "order_items".* FROM "order_items" WHERE "order_items"."order_id" = ?  [["order_id", 4]]
  Rendered order_items/index.html.erb within layouts/application (15.0ms)
  CACHE  (0.1ms)  SELECT SUM("order_items"."quantity") FROM "order_items" WHERE "order_items"."order_id" = ?  [["order_id", 4]]
  Rendered layouts/_header.html.erb (22.0ms)
  Rendered layouts/_footer.html.erb (1.9ms)
Completed 200 OK in 1313ms (Views: 1304.9ms | ActiveRecord: 2.1ms)

1 个答案:

答案 0 :(得分:0)

您每次调用add_item方法时都在搜索椅子项目,因此由于未传递椅子ID而抛出错误,因此您需要按以下方式修改方法

def add_item(chair_id:, bookcabinet_id:, quantity: 1)
chair = Chair.find(chair_id) if chair_id
bookcabinet = Bookcabinet.find(bookcabinet_id) if bookcabinet_id

order_item = order.items.find_or_initialize_by(
  chair_id: chair_id,
  bookcabinet_id: bookcabinet_id
)

order_item.price = chair.price if chair
order_item.price = bookcabinet.price

order_item.quantity = quantity

ActiveRecord::Base.transaction do
  order_item.save
  update_sub_total!
end

结束

请随时询问是否有与此相同的问题