简体   繁体   中英

has_one and has_many association in Rails

I am a bit confused as to what to do with this association.

Models

class Loan < ActiveRecord::Base
  has_many: payments
end

class Payment < ActiveRecord::Base
  belongs_to: loan
end

The confusion comes in because theoretically a person can payoff the loan in one payment, thus, there wouldn't be 'many' payments.

Can Loan have both has_one and has_many at the same time?

Thanks

has_many doesn't mean must_have_many , but rather can_have_many

In fact, your loan could have zero or a hundred payments, the relationship should still be has_many .

You will also still need to access the single payment as a collection of payments, even though there may only be one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM