Can has_one association be used when the model has one or zero instances of another model?

跟風遠走 提交于 2019-12-03 12:15:39

has_one is correct - the relationship that's set up is not mandatory unless you add your own validations to it.

To make it a bit clearer -

class Post < ActiveRecord::Base
  has_one :author

end

class Author < ActiveRecord::Base
  belongs_to :post 

end

With no validations, a given post can have an author (but not more than one) - however an author is not necessary.

Unless you define specific validations, has_one just prevents you from having more than one object associated to your model. Zero is ok.

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