Denny Mueller
Denny Mueller

Reputation: 3615

has_many and belongs_to how to reference the relationship both ways

I have a model invoice and a model invoice_layout.

invoice
  belongs_to invoice_layout
end

(the invoice table has a invoice_layout_id)

invoice_layout
  has_many invoices
end

Can I just reference invoice_layout.invoice or does it work in both directions so that i can call invoice.invoice_layout ? If that is not possible, how can i achieve that?

best regards denym_

Upvotes: 0

Views: 52

Answers (2)

Mandeep
Mandeep

Reputation: 9173

yes it works both ways for example if you want to refer a invoice from a invoice_layout you'll use invoice_layout.invoices and if you want to refer to a invoice_layout from a invoice you can do invoice.invoice_layout. But for them to work properly first you need to find that particular invoice_layout or invoice from which you want to refer the other one

Upvotes: 0

Marek Lipka
Marek Lipka

Reputation: 51151

With these associations, you have methods Invoice#invoice_layout and InvoiceLayout#invoices generated.

Upvotes: 1

Related Questions