嘿傢伙我想發送一個電子郵件在rails當我點擊訂單按鈕到用戶的電子郵件ID,但我得到這個錯誤,當我點擊按鈕undefined method 'items' for #<Order:0x6d83c48>
這我的order_mailer.rb在郵件文件夾需要幫助發送電子郵件通知在欄杆
class OrderMailer < ActionMailer::Base
default from: "[email protected]"
def order_confirmation order
@order=order
mail to: order.user.email, subject: "Your order (##{order.id})"
end
end
,這是我orders_controller.rb
class OrdersController < ApplicationController
def create
@order_form=OrderForm.new(user: User.new(order_params[:user]),cart: @cart)
if @order_form.save
notify_user
redirect_to root_path,notice:"Thank You for placing the order sir."
else
render "carts/checkout"
end
end
private
def notify_user
OrderMailer.order_confirmation(@order_form.order).deliver
end
def order_params
params.require(:order_form).permit(
user:[:name,:phone,:address,:city,:country,:postal_code,:email])
end
end
,最後我的意見/ order_mailer文件夾order_confirmation.text.erb
<h2>Hello</h2><%[email protected]%>,
Thank you for placing an order. Here is a summary for order #<%[email protected]%>:
<% @order.items.each do |item|%>
*<%=item.quantity%><%=item.product.name%>($<%=item.total_price%>)
<%end%>
Total: $<%[email protected]_price%>
@ order.user.name工作正常,但是, 我不知道爲什麼它不能找到,爲了能有人告訴我什麼是錯的物品的方法,因爲我只是不能似乎弄明白
cart.rb
class Cart
attr_reader :items
def self.build_from_hash (hash)
items= if hash["cart"] then
hash["cart"]["items"].map do |item_data|
CartItem.new item_data["product_id"],item_data["quantity"]
end
else
[]
end
new items
end
def initialize items=[]
@items=items
end
def add_item (product_id)
[email protected] { |item| item.product_id == product_id}
if item
item.increment
else
@items << CartItem.new(product_id)
end
end
def empty?
@items.empty?
end
def count
@items.length
end
def grand_total
@items.inject(0){|sum,item| sum+item.total_price}
end
def serialize
items = @items.map do |item|
{
"product_id" =>item.product_id,
"quantity" => item.quantity
}
end
{
"items" => items
}
end
end
order_item.rb
class OrderItem < ApplicationRecord
belongs_to :order
belongs_to :product
def total_price
self.product.price*self.quantity
end
end
cart_item.rb
class CartItem
attr_reader :product_id,:quantity
def initialize (product_id,quantity=1)
@product_id=product_id
@quantity=quantity
end
def increment
@[email protected]+1
end
def product
Product.find product_id
end
def total_price
product.price*quantity
end
end
你可以分享order.rb文件。你是否正確定義了關聯? – Sajin
這些是模型 –
類訂單