我想在Ruby on Rails上做一個簡單的圖書訂購應用程序,並且遇到了一些問題。我試圖從每個產品的鏈接中創建一個「訂購」頁面,以便在第二頁上顯示書籍信息,然後填寫顧客需要的數量。然而,我一直運行到上面指定的nil:NilClass錯誤的未定義方法'book_id'中(並且當我刪除那行代碼時,我在下一行中遇到相同的錯誤 - 即未定義的方法'order_id')。未定義的方法'book_id'爲零:NilClass
這裏是我的,我一直在搞亂視圖代碼:
<%= @order_item.book_id %>
<%= @order_item.order_id %>
<%= @order_item.total_pricel %>
<%= form_for @order_item.quantity do |f| %>
<%= f.label :quantity %>:
<%= f.text_field :quantity %><br />
<%= f.submit %>
<% end %>
我OrderItem的模型應該有外鍵ORDER_ID和book_id。
這裏是我的OrderItem的模型:
class OrderItem < ActiveRecord::Base
belongs_to :order
belongs_to :book
validates :quantity, presence: true, numericality: {only_integer: true, greater_than: 0}
validate :book_present
validates :price, presence: true
validate :order_present
def unit_price
if persisted?
self[:unit_price]
else
book.price
end
end
def total_price
unit_price * quantity
end
private
def book_present
if book.nil?
errors.add(:book, "is not valid.")
end
end
def order_present
if order.nil?
errors.add(:order, "is not a valid order.")
end
end
def finalize
self[:unit_price] = unit_price
self[:total_price] = quantity * self[:unit_price]
end
end
而這裏的控制器:
class OrderItemsController < ApplicationController
def create
@order = current_order
@order_item = @order.order_items.new(order_item_params)
@order.save
session[:order_id] = @order.id
end
def update
@order = current_order
@order_item = @order.order_items.find(params[:id])
@order_item.update_attributes(order_item_params)
@order_items = @order.order_items
end
def destroy
@order = current_order
@order_item = @order.order_items.find(params[:id])
@order_item.destroy
@order_item = @order.order_items
end
private
def order_item_params
params.require(:order_item).permit(:quantity, :book_id)
end
end
除了這個是我第一次的Rails項目,我一般很新的編碼,真的希望一些幫助!