问题
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