简体   繁体   English

Rails 中的 has_one 和 has_many 关联

[英]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? Loan 可以同时拥有 has_one 和 has_many 吗?

Thanks谢谢

has_many doesn't mean must_have_many , but rather can_have_many has_many并不意味着must_have_many ,而是can_have_many

In fact, your loan could have zero or a hundred payments, the relationship should still be has_many .事实上,你的贷款可能有零或一百个付款,关系应该仍然是has_many

You will also still need to access the single payment as a collection of payments, even though there may only be one.您还需要将单笔付款作为付款集合访问,即使可能只有一笔付款。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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