2013-12-14 158 views
0

我有这样的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 (?, ?, ?, ?, ?)

我在做什么错?

回答

1

尝试

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 

,但第一种形式是比较常见的。如果您将类似productmember的对象分配给关联,则Rails非常聪明,可以向该对象询问其ID并自动使用它。

另外,Product.where可能会返回多个结果。由于您只希望有一个,请添加.first以仅返回第一个匹配项。

+0

谢谢,如果我必须检索此产品的ID,该怎么办?将更新问题。 – hansottowirtz

+0

我不确定我是否理解 - 您确实拥有该产品。如果你确实需要模型ID,你可以使用'current_member.id'完成你的工作,并在'.first'之后添加'.id'。 – janfoeh

+0

这可能是一个愚蠢的错误,但我现在有这样的代码: “产品= 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

1

根据Rails的版本,你应该能够:

的Rails 3: Product.find_by_barcode_number(params[:barcode_number])

轨道4,5: 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

+0

我已经找到它了,但是感谢格式化问题!如果我有超过15的声望,我肯定会投票,哈哈。 – hansottowirtz

+0

@ xprise哈哈!别担心。 –

相关问题