gpt4 book ai didi

ruby-on-rails - Rails 4.0 未定义方法 `+' 为 nil :NilClass

转载 作者:太空宇宙 更新时间:2023-11-03 18:17:10 25 4
gpt4 key购买 nike

我正在尝试向我的 orders_items Controller 添加一行,因此如果它是一个新订单,则将计数器从零递增到一。所以在调用保存之前创建了一个执行此操作的操作但是当我尝试它时我得到:

undefined method `+' for nil:NilClass
def create
@order_item = @order.order_items.find_or_initialize_by_product_id(params[:product_id])
# Error below
@order_item.quantity += 1

respond_to do |format|
if @order_item.save
end
end

order_item.rb:

class OrderItem < ActiveRecord::Base
belongs_to :order
belongs_to :product

validates :order_id, :product, presence: true
validates :quantity, numericality: { only_integer: true, greater_than: 0 }

def subtotal
quantity * product.price
end
end

order_items_controller.rb:

class OrderItemsController < ApplicationController
before_action :set_order_item, only: [:show, :edit, :destroy]
before_action :load_order, only: [:create]

# GET /order_items
# GET /order_items.json
def index
@order_items = OrderItem.all
end

# GET /order_items/new
def new
@order_item = OrderItem.new
end

# POST /order_items
# POST /order_items.json
def create
@order_item = @order.order_items.find_or_initialize_by_product_id(params[:product_id])
@order_item.quantity += 1

respond_to do |format|
if @order_item.save
format.html { redirect_to @order, notice: 'Successfully added product to cart.' }
format.json { render action: 'show', status: :created, location: @order_item }
else
format.html { render action: 'new' }
format.json { render json: @order_item.errors, status: :unprocessable_entity }
end
end
end

# PATCH/PUT /order_items/1
# PATCH/PUT /order_items/1.json
def update
@order_item = OrderItem.find(params[:id])
respond_to do |format|
if order_item_params[:quantity].to_i == 0
@order_item.destroy

format.html { redirect_to @order_item.order, notice: 'Order item was successfully updated.' }
format.json { head :no_content }

elsif @order_item.update(order_item_params)

format.html { redirect_to @order_item.order, notice: 'Successfully updated the order item.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @order_item.errors, status: :unprocessable_entity}
end
end
end

# DELETE /order_items/1
# DELETE /order_items/1.json
def destroy
@order_item.destroy
respond_to do |format|
format.html { redirect_to @order_item.order }
format.json { head :no_content }
end
end

private
# Use callbacks to share common setup or constraints between actions.

def load_order
@order = Order.find_or_initialize_by_id(session[:order_id], status: "unsubmitted")
if @order.new_record?
@order.save!
session[:order_id] = @order.id
end
end

def set_order_item
@order_item = OrderItem.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def order_item_params
params.require(:order_item).permit(:product_id, :order_id, :quantity)
end
end

迁移文件:

class AddDefaultQuantityToOrderItems < ActiveRecord::Migration
def change
change_column :order_items, :quantity, :integer, default: 0
end
end

rails 控制台:

@order.order_items.find_or_initialize_by_product_id(params[:product_id])
NoMethodError: undefined method `order_items' for nil:NilClass
from (irb):1
from /usr/local/rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.4/lib/rails/commands/console.rb:90:in `start'
from /usr/local/rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.4/lib/rails/commands/console.rb:9:in `start'
from /usr/local/rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.4/lib/rails/commands.rb:62:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'

模型order.rb:

class Order < ActiveRecord::Base

has_many :order_items, dependent: :destroy

def total
order_items.map(&:subtotal).sum
end

end

orders_controller.rb:

class OrdersController < ApplicationController
before_action :set_order, only: [:show, :edit, :update, :destroy]

# GET /orders
# GET /orders.json
def index
@orders = Order.all
end

# GET /orders/1
# GET /orders/1.json
def show
end

# GET /orders/new
def new
@order = Order.new
end

# GET /orders/1/edit
def edit
end

# POST /orders
# POST /orders.json
def create
@order = Order.new(order_params)

respond_to do |format|
if @order.save
format.html { redirect_to @order, notice: 'Order was successfully created.' }
format.json { render action: 'show', status: :created, location: @order }
else
format.html { render action: 'new' }
format.json { render json: @order.errors, status: :unprocessable_entity }
end
end
end

# PATCH/PUT /orders/1
# PATCH/PUT /orders/1.json
def update
respond_to do |format|
if @order.update(order_params)
format.html { redirect_to @order, notice: 'Order was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @order.errors, status: :unprocessable_entity }
end
end
end

# DELETE /orders/1
# DELETE /orders/1.json
def destroy
@order.destroy
respond_to do |format|
format.html { redirect_to products_path }
format.json { head :no_content }
end
end

private
# Use callbacks to share common setup or constraints between actions.
def set_order
@order = Order.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def order_params
params.require(:order).permit(:user_id, :status)
end
end

更新

Rake routes 显示/:product_id 的路由调用

产品.rb

class Product < ActiveRecord::Base
validates_numericality_of :price
validates :stock ,numericality: { greater_than_or_equal_to: 0 }
end

订单.rb

# @Chiperific added proper 4-line indentation for SO viewing.
class OrderItem < ActiveRecord::Base
belongs_to :order
belongs_to :product

validates :order_id, :product, presence: true
validates :quantity, numericality: { only_integer: true, greater_than: 0 }


def subtotal
quantity * product.price
end
end

订单商品.rb

class OrderItem < ActiveRecord::Base
belongs_to :order
belongs_to :product

validates :order_id, :product, presence: true
validates :quantity, numericality: { only_integer: true, greater_than: 0 }


def subtotal
quantity * product.price
end
end

当我添加

def create
@order_item = OrderItems.find_or_initialize_by_product_id(params[:product_id])
@order_item.quantity +=1

我在 OrderItemsController#create 中得到 NameError - 未初始化的常量 OrderItemsController::Orderitems

定义创建 @order_item = Orderitems.find_or_initialize_by_product_id(params[:product_id]) <-错误 @order_item.quantity += 1

如果我尝试

@order = Order.find(params[:order_id])
@order_item = @order.order_items.find_or_initialize_by_product_id(params[:product_id])
@order_item.quantity += 1

我在 OrderItemsController 中得到 ActiveRecord::RecordNotFound#create - 找不到没有 ID 的订单

def create
@order = Order.find(params[:order_id])
@order_item = @order.order_items.find_or_initialize_by_product_id(params[:product_id])<-error
@order_item.quantity += 1

最佳答案

我看不到 @order 的定义位置。由于 @order 为空,因此 @order_items 也将为空。

我假设您的 View URL 类似于 /orders/:order_id/order_items/:id因此,让我们使用 URL 参数来确保您获得 OrderOrder_ID 启动。

选项 1:不用担心@order

def create
@order_item = OrderItem.find_or_initialize_by_product_id(params[:product_id])
@order_item.quantity +=1

...

end

选项 2:先设置 `@order`

def create
@order = Order.find(params[:order_id])
@order_item = @order.order_items.find_or_initialize_by_product_id(params[:product_id])
@order_item.quantity += 1

...

end

其他潜在问题:

.find_or_initialize_by_product_id(params[:product_id]) 实际上不是查找初始化

看起来这是你的表关系:

[Orders]`````\
|--> [Order_Items]
[Products]___/
  1. 我看不到 orders.rb 中的 accepts_nested_attributes_for :order_items 的位置
  2. 您可能还需要 products.rb 中的 accepts_nested_attributes_for :order_items
  3. Order_Item 记录是否有 Product_id 字段?我看到您在哪里验证 :product 的存在,但不是 :product_id,您的架构是什么样的?如果你尝试 `find__or_initialize_by_product(params[:product_id]) 会发生什么?
  4. 您的路线是否调用 /:product_id/:product 或两者都不调用? (也就是有 params[:product_id] 吗?)

更新:

感谢更新的评论。请添加正在使用的整个 URI、整个 Rake Routes 行或 Routes.rb 文件。或者,虽然我知道这不是最佳实践,但您可以在 Github 上发布该项目的链接,我会在那里查看。

我仍然相信(至少一个)问题是未设置@order。

在 Rails 控制台中试用它是了解 .find_or_initialize_by_product_id 是否正常工作的好方法

但是,rails console 不能拉取参数而且你仍然没有先分配@order。要进行测试,请在 Rails 控制台中尝试:

@order = Order.first #<----(just so you get @order assigned)
@order.order_items.find_or_initialize_by_product_id(1)

还有:

@order_item = OrderItems.find_or_initialize_by_product_id(params[:product_id])

OrderItems 应该是单数的(我的错!!):

@order_item = OrderItem.find_or_initialize_by_product_id(params[:product_id])

我会更加关注这篇文章并更加及时地发布我的文章,因为我相信您会感到沮丧。坚持住,你的方法很好。

但是,如果我们不能解决这些问题,可能还有另一种方法。我们可以通过计算具有特定订单 ID 的记录数来找到订单商品数量,而不是将数字静态保存在数据库中吗?如果您准备好解决这个问题,请考虑一下。

关于ruby-on-rails - Rails 4.0 未定义方法 `+' 为 nil :NilClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24342973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com