newUserNameHere
newUserNameHere

Reputation: 17971

Create new active record object with relationship?

I understand you can do something like this:

# Payment belongs_to Product 
# Product has_many Payments
product_id = Product.find_by_name("widget").id
Payment.new(product_id: product_id)

This works, but is it possible to do something like this?

Payment.new(product: {name: "widget})

This throws an error, but perhaps my syntax is just off? Any help would be greatly appreciated.

Upvotes: 0

Views: 148

Answers (1)

Rustam Gasanov
Rustam Gasanov

Reputation: 15781

You are going wrong way, consider this

product = Product.where(name: "widget").first
product.payments.new # payment will have correct product_id automatically

Upvotes: 2

Related Questions