can Belongs_to work without has_many or has_one

不问归期 提交于 2019-12-05 17:26:11

Technically, belongs_to will work without a matching has_many or has_one. If, for instance, you say that Order belongs_to :customer, you can call .customer on an Order object, and get a Customer object. What you can't do is call .orders on a Customer without telling it that it has_many :orders (or .order, in the case of has_one), because that method is created by the has_many declaration.

That said, I can't think of any reason you would ever want to only specify half of a relation. It's a terrible design choice, and you should not do it.

Edit: has_one doesn't create the .collection methods that has_many does. Per the guide:

4.2.1 Methods Added by has_one

When you declare a has_one association, the declaring class automatically gains four methods related to the association:

association(force_reload = false) 
association=(associate)
build_association(attributes = {}) 
create_association(attributes = {})

You'll note that there's no .new on that list. If you want to add an associated object, you can use customer.build_order(), or customer.order = Order.new().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!