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.
They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.
Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.
In Rails, an association is a connection between two Active Record models. Why do we need associations between models? Because they make common operations simpler and easier in your code. For example, consider a simple Rails application that includes a model for authors and a model for books.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With