Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 473
user2725109 Avatar asked Sep 25 '13 12:09

user2725109


People also ask

What is the difference between Has_one and Belongs_to?

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.

What is a polymorphic association in Rails?

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.

What is Associations in Rails?

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.


1 Answers

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.

like image 88
dax Avatar answered Oct 12 '22 11:10

dax