現在、railsでecサイトを作成していて、その中でカートの機能を実装中なのですが、詰まっているのでご質問させていただいきます。
現在、リンク内容こちらのキータを参考にカートを作成しています。
今やりたくてできないことは、カートボタンを押した際に、postでその選んだ商品名と数量を、cart_itemテーブルに保存したいのですが、
cartcontroller
1class CartsController < ApplicationController 2 before_action :setup_cart_item!, only: [:add_item, :update_item, :delete_item] 3 4 def show 5 @cart_items = current_cart.cart_items 6 end 7 8 # 商品一覧画面から、「商品購入」を押した時のアクション 9 def add_item 10 if @cart_item.blank? 11 @cart_item = current_cart.cart_items.build(product_id: params[:product_id]) 12 end 13 14 @cart_item.quantity += params[:quantity].to_i 15 @cart_item.save 16 redirect_to current_cart 17 end 18 19 def update_item 20 @cart_item.update(quantity: params[:quantity].to_i) 21 redirect_to current_cart 22 end 23 24 def delete_item 25 @cart_item.destroy 26 redirect_to current_cart 27 end 28 29 private 30 31 def setup_cart_item! 32 @cart_item = current_cart.cart_items.find_by(product_id: params[:product_id]) 33 end 34end
上記のように、cart_itemsメソッドが定義されてないとエラーが出されるのですが、上記の参考キータ記事のように、cart_itemモデルを作成して、cartモデルとのリレーション関係を記入しました(belogs_to,has_many)。
なぜ、上記の関係を定義しているのにcart_controller内で、cart_itemsメソッドが使えないのでしょうか?
長くなりましたが、ご回答お願いします。
よくエラーメッセージを見ましょう。Integer 41 に cart_items メソッドなんてないです。参照記事も不十分です。cart_item が存在しなかったら、またエラーになりますよ。
cart_itemというメソッドも定義しなければいけないのでしょうか?
cart_itemモデルが存在していれば、このメソッドは自動で生成されると思っていたのですが、、
cart_items というメソッドは Cart クラスにおいて(自動)定義されるものです。エラーをもう一度よく確認してください。エラーは Integer クラスに対して cart_items メソッドを実行しています。current_cart というメソッドが Integer を返していると想像されます。なぜそうなったのか、確認してみてください。
current_cartメソッドの中でcart_idを@cartに入れているからでしょうか?(cart_idがintegerなので)
結局、レコードに対して、cart_itemsメソッドを実行すればいいのでしょうか?
なんか、わかりそうでわからないです。。
まず current_cart メソッドの定義を(ファイル内すべてを)お示しください。また参考URLの通りに実施しているのか、いないならどこがどう違うのか、お示しください。
Screen Shot 2019-01-21 at 19.06.13
全て参考URLどうりに行っています。。
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
include SessionsHelper
helper_method :current_cart
def current_cart
if session[:cart_id]
@cart = Cart.find(session[:cart_id])
else
@cart = Cart.create
session[:cart_id] = @cart.id
end
end
end
current_cartの中身です。。
あなたの回答
tips
プレビュー