Rails属于双向

时间:2018-10-02 05:04:51

标签: ruby-on-rails

我有一张样板机票和一张样板收据。收据具有属性ticket_id。

receipt.rb

belongs_to :ticket

一张收据总是只有一张票,而一张票只有一张收据。

现在我可以打电话给receive.ticket。但是我打不了ticket.receipt。

有没有一种方法可以在不向Ticket添加票证属性的情况下实现?

2 个答案:

答案 0 :(得分:4)

has_one

receipt.rb

belongs_to :ticket

ticket.rb

has_one :receipt
#has_one :receipt, class_name: "Receipt", foreign_key: "ticket_id"

..

#receipt.ticket =>  Returns the associated ticket. nil is returned if none is found.
#ticket.receipt =>  Returns the associated receipt. nil is returned if none is found.

答案 1 :(得分:0)

在ticket.rb中,添加:

has_one :receipt