我有这样的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