【发布时间】:2014-10-16 06:55:43
【问题描述】:
我正在关注使用 Rails 4 进行敏捷 Web 开发。第 9 章购物车创建。当我想更新购物车时,我收到以下错误通知:分配属性时,您必须将哈希作为参数传递。 CartController#update.
class CartsController < ApplicationController
include CurrentCart
before_action :set_cart, only: [:show, :edit, :update, :destroy]
rescue_from ActiveRecord::RecordNotFound, with: :invalid_cart
def index
@carts = Cart.all
end
def show
end
def new
@cart = Cart.new
end
def edit
end
def create
@cart = Cart.new(cart_params)
respond_to do |format|
if @cart.save
format.html { redirect_to @cart, notice: 'Cart was successfully created.' }
format.json { render :show, status: :created, location: @cart }
else
format.html { render :new }
format.json { render json: @cart.errors, status: :unprocessable_entity }
end
end
end
def update
@cart = Cart.find(params[:id])
respond_to do |format|
if @cart.update_attributes(params[:cart])
format.html { redirect_to @cart, notice: 'Cart was successfully updated.' }
format.json { render :show, status: :ok, location: @cart }
else
format.html { render :edit }
format.json { render json: @cart.errors, status: :unprocessable_entity }
end
end
end
def destroy
@cart.destroy if @cart.id == session[:card_id]
session[:card_id] = nil
respond_to do |format|
format.html { redirect_to store_url, notice: 'Your cart is currently empty.' }
format.json { head :no_content }
end
end
private
def set_cart
@cart = Cart.find(params[:id])
end
def cart_params
params[:cart]
end
def invalid_cart
logger.error "Attempt to access invalid cart #{params[:id]}"
redirect_to store_url, notice: 'Invalid cart'
end
end
【问题讨论】:
-
你的
params[:cart]是什么样的?那不是哈希吗?你能检查参数并分享结果吗? -
这就是日志文件中的内容。在 2014-10-17 21:10:24 +0200 为 127.0.0.1 开始 PATCH "/carts/32" 处理由 CartsController#update 作为 HTML 参数:{"utf8"=>"✓", "authenticity_token"=>" N/VxeEOEbfYQhhEcPqMnzUPZVLxZqecS4BwJjHivqi4=", "commit"=>"Update Cart", "id"=>"32"} 购物车加载 (0.1ms) SELECT "carts".* FROM "carts" WHERE "carts"."id" = ? LIMIT 1 [["id", 32]] (0.0ms) begin transaction (0.1ms) rollback transaction Completed 500 Internal Server Error in 2ms
-
ArgumentError(分配属性时,必须将哈希值作为参数传递。):app/controllers/carts_controller.rb:49:in
block in update' app/controllers/carts_controller.rb:47:inupdate'
标签: ruby-on-rails