我知道你可以这样做:
# Payment belongs_to Product
# Product has_many Payments
product_id = Product.find_by_name("widget").id
Payment.new(product_id: product_id)
这样可行,但可以这样做吗?
Payment.new(product: {name: "widget})
这会引发错误,但也许我的语法只是关闭?任何帮助将不胜感激。
答案 0 :(得分:2)
你走错了路,考虑一下
product = Product.where(name: "widget").first
product.payments.new # payment will have correct product_id automatically