1
我試圖在產品保存在我的產品控制器中時創建事務日誌。出於某種原因,當我嘗試保存事務日誌時出現錯誤。該產品正在成功保存。爲什麼模型創建不起作用
代碼:
def create
@product = Product.new(params[:product])
respond_to do |format|
if @product.save
ProductTransaction.create(
:product_id => @product.id,
:user_id => current_user.id,
:message => "Product created"
)
format.html {
redirect_to product_path(@product.id),
:flash => { :success => "Product was successfully created." }
}
else
format.html { render action: "new" }
end
end
end
錯誤:
PGError: ERROR: column "product_id" is of type integer but expression is of type character varying at character 117
HINT: You will need to rewrite or cast the expression.
: INSERT INTO "product_transactions" ("created_at", "message", "product_id", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5) RETURNING "id"
我不明白上面的錯誤。我仔細檢查了我的表,並且product_id是一個整數。此外,我努力編碼一個數字,看看我是否可以保存它。這沒有用。然後我刪除了創建函數中的所有參數,但仍得到相同的錯誤。我甚至從零開始重新創建了表格並獲得了相同的結果。 ProductTransaction沒有驗證要求。我究竟做錯了什麼?
代碼(刪除參數):
def create
@product = Product.new(params[:product])
respond_to do |format|
if @product.save
ProductTransaction.create()
format.html {
redirect_to product_path(@product.id),
:flash => { :success => "Product was successfully created." }
}
else
format.html { render action: "new" }
end
end
end
產品架構:
Product(id:integer, name:string, etc.)
產品交易模式:
ProductTransaction(id:integer, user_id:integer, product_id:integer, message:integer)
什麼是'@ product.id'?我們看不到表格模式,因此很難猜測。 – 2013-03-06 19:45:29
你在使用回調嗎?您的產品模型中可能是'before_create'?如果沒有,也許你在某個地方設置了默認值?假設你正確地設置了你的關聯,你可能還想嘗試給'@ product.product_transactions.build(...)'替換'create'。這會爲你設置'product_id'。 – Noz 2013-03-06 19:47:07
no before_create回調 – 2013-03-06 19:52:05