I'm getting the following error, unknown attribute 'size' for OrderItem.
when I try to "checkout" with an item in a shopping cart that I created using Ruby on Rails. At first, the cart just managed the product_id and the quantity, but now I need to add a size attribute to products. I modified my class files to the following,
order_form.rb
class OrderForm
include ActiveModel::Model
attr_accessor :user, :order, :shipping_price # credit_card
attr_writer :cart
def save
set_password_for_user
if valid?
persist
true
else
false
end
end
def has_errors?
user.errors.any?
end
private
def valid?
user.valid?
end
def persist
puts "inside persis shipping_price : #{shipping_price.inspect}"
user.save
@order = Order.create! user: user, shipping_price: shipping_price
build_order_items
end
def set_password_for_user
user.password = Digest::SHA1.hexdigest(user.email + Time.now.to_s)[0..8]
end
def build_order_items
@cart.items.each do |item|
@order.order_items.create! product_id: item.product_id, quantity: item.quantity, size: item.size
end
end
end
order_item.rb
class OrderItem < ActiveRecord::Base
belongs_to :order
belongs_to :product
def total_price
self.quantity * self.product.price
end
end
cart_item.rb
class CartItem
attr_reader :product_id, :quantity, :size
def initialize product_id, quantity = 1, size
@product_id = product_id
@quantity = quantity
@size = size
end
def increment
@quantity = @quantity + 1
end
def product
Product.find product_id
end
def total_price
# puts "Hello cart_item"
product.price * quantity
end
end
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"], item_data["size"]
end
else
[]
end
new items
end
def initialize items = []
@items = items
end
def add_item product_id, size
item = @items.find { |item| item.product_id == product_id
item.size == size }
if item
item.increment
else
@items << CartItem.new(product_id, size)
end
end
def empty?
@items.empty?
end
def count
@items.length
end
def serialize
items = @items.map do |item|
{
"product_id" => item.product_id,
"quantity" => item.quantity,
"size" => item.size
}
end
{
"items" => items
}
end
def total_price(shipping_price = 0)
# puts "Hello cart"
@items.inject(0) { |sum, item| sum + item.total_price } + shipping_price
end
end
create_order_items.rb
class CreateOrderItems < ActiveRecord::Migration
def change
create_table :order_items do |t|
t.references :order, index: true, foreign_key: true
t.references :product, index: true, foreign_key: true
t.integer :quantity
t.timestamps null: false
end
end
end
答案 0 :(得分:1)
it looks like you are calling .size on an OrderItems instance here:
def build_order_items
@cart.items.each do |item|
@order.order_items.create! product_id: item.product_id, quantity: item.quantity, size: item.size
end
end
P.S. Please for the love of humanity start using parens.