我有這樣的Rails代碼:Ruby on Rails的:ActiveRecord的:: StatementInvalid不能施放的ActiveRecord :: StatementInvalid
def newfood
memberproduct = MemberProduct.new
memberproduct.product_id = Product.where(:barcode_number => params[:barcode_number]).id
memberproduct.expiration_date = params[:expiration_date]
memberproduct.member_id = current_member.id
memberproduct.save
end
我所需要的產品的ID。 第三行是錯誤的。
我有一個MemberProduct
表與product_id
字段,expiration_date
字段和member_id
字段(current_member來自devise
) 我有一個Product
表與barcode_number
字段和name
字段。
我得到這個錯誤:
ActiveRecord::StatementInvalid in FoodController#newfood TypeError: can't cast ActiveRecord::Relation::ActiveRecord_Relation_Product to string: INSERT INTO "member_products" ("created_at", "expiration_date", "member_id", "product_id", "updated_at") VALUES (?, ?, ?, ?, ?)
我在做什麼錯?
謝謝,如果我必須檢索此產品的ID,該怎麼辦?將更新問題。 – hansottowirtz
我不確定我是否理解 - 您確實擁有該產品。如果你確實需要模型ID,你可以使用'current_member.id'完成你的工作,並在'.first'之後添加'.id'。 – janfoeh
這可能是一個愚蠢的錯誤,但我現在有這樣的代碼: 「產品= Product.where(:barcode_number => PARAMS [:barcode_number])。第一 memberproduct = MemberProduct.new memberproduct.product_id = product.id memberproduct.expiration_date = params [:expiration_date] memberproduct.member_id = current_member.id memberproduct。保存' 而且它說無定義方法'id'爲零:NilClass 但是,已經表示感謝! – hansottowirtz