hey guys i want to send an email in rails when i click the place order button to a user email id but i get this error when i click the button undefined method 'items' for #<Order:0x6d83c48>
this my order_mailer.rb in mailer folder
class OrderMailer < ActionMailer::Base
default from: "gokuverma94@gmail.com"
def order_confirmation order
@order=order
mail to: order.user.email, subject: "Your order (##{order.id})"
end
end
and this is my 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
and finally my order_confirmation.text.erb in the views/order_mailer folder
<h2>Hello</h2><%=@order.user.name%>,
Thank you for placing an order. Here is a summary for order #<%=@order.id%>:
<% @order.items.each do |item|%>
*<%=item.quantity%><%=item.product.name%>($<%=item.total_price%>)
<%end%>
Total: $<%=@order.total_price%>
@order.user.name is working fine but, I dont know why it cannot find the items method in order can someone please tell me what is wrong with it because i just cant seem to figure it out
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)
item=@items.find { |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
@quantity=@quantity+1
end
def product
Product.find product_id
end
def total_price
product.price*quantity
end
end