gpt4 book ai didi

ruby-on-rails - 分配属性时,必须传递一个散列作为参数

转载 作者:行者123 更新时间:2023-12-04 01:59:16 25 4
gpt4 key购买 nike

我正在关注 Rails 4 的敏捷 Web 开发。第 9 章购物车创建。当我想更新购物车时,我收到以下错误通知:分配属性时,您必须将散列作为参数传递。购物车 Controller #更新。

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

最佳答案

您的参数可能是 ActionController::Parameters 的一个实例

如果是这样,您需要允许要使用的属性,如下所示:

def cart_params
params.require(:cart).permit(:attribute1, :attribute2, :attribute3)
end

关于ruby-on-rails - 分配属性时,必须传递一个散列作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26398020/

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