![](/img/trans.png)
[英]ActiveRecord::StatementInvalid ruby on rails 3.2
[英]Ruby on Rails: ActiveRecord::StatementInvalid can't cast ActiveRecord::StatementInvalid
我有這個Rails代碼:
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。 第3行錯了。
我有一個帶有product_id
字段的MemberProduct
表,一個expiration_date
字段和一個member_id
字段(current_member來自devise
)我有一個帶有barcode_number
字段和name
字段的Product
表。
我收到此錯誤:
FoodController中的ActiveRecord :: StatementInvalid #newfood TypeError:無法將ActiveRecord :: Relation :: ActiveRecord_Relation_Product轉換為字符串:INSERT INTO“member_products”(“created_at”,“expiration_date”,“member_id”,“product_id”,“updated_at”)價值觀(?,?,?,?,?)
我究竟做錯了什么?
嘗試
memberproduct.product = Product.where(:barcode_number => params[:barcode_number]).first
memberproduct.product_id
是數據庫列,其中Rails存儲與您的memberproduct關聯的產品的ID。 通常,這些不是直接使用的; 相反,關聯名稱是。
所以這兩個工作:
def newfood
memberproduct = MemberProduct.new
product = Product.where(:barcode_number => params[:barcode_number]).first
memberproduct.product = product
memberproduct.expiration_date = params[:expiration_date]
memberproduct.member = current_member
memberproduct.save
end
和
def newfood
memberproduct = MemberProduct.new
product = Product.where(:barcode_number => params[:barcode_number]).first
memberproduct.product_id = product.id
memberproduct.expiration_date = params[:expiration_date]
memberproduct.member_id = current_member.id
memberproduct.save
end
但第一種形式更常見。 如果您將對象(如product
或member
分配給關聯,則Rails足夠聰明,可以向對象詢問其ID並自動使用它。
此外, Product.where
可能會返回多個結果。 因為你只想要一個,所以添加.first
只返回第一個匹配。
根據Rails的版本,您應該能夠:
Rails 3: Product.find_by_barcode_number(params[:barcode_number])
Rails 4: Product.find_by(barcode_number: params[:barcode_number])
您可以這樣簡化操作:
mprod = current_member.build_member_product(expiration_date: params[:expiration_date])
mprod.product = Product.find_by(barcode_number: params[:barcode_number])
mprod.save
雖然您可能想要處理驗證等( if mprod.save .. else
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.