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

耗尽温柔 提交于 2019-12-04 18:17:29

问题


RailsGuides says:

http://guides.rubyonrails.org/association_basics.html A has_many "association indicates that each instance of the model has zero or more instances of another model."

"A has_one association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences). This association indicates that each instance of a model contains or possesses one instance of another model."

Does that mean if I want to set up an association that each instance of the model has zero or one instance of another model, the best way is to use has_many and not has_one? What will be the problems I'll encounter if I use has_one?

Thanks.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/19005296/can-has-one-association-be-used-when-the-model-has-one-or-zero-instances-of-anot

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