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

2

12

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.

Slosh answered 25/9, 2013 at 12:44 Comment(0)
W
19

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.

Width answered 25/9, 2013 at 12:49 Comment(0)
S
6

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

Swank answered 25/9, 2013 at 12:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.