Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a model with has_one contraint

I want to create 2 models, where one belongs to another. I know the generate command to create a model that “belongs_to” another but I have no clue how to have the other model have “has_one”.

Can I specify “has_one” in the generate command? Or do I manually add it to the model file after?

This still confuses me since the child that “belongs_to” has the foreign key and the parent that “has_one” doesn’t have anything.

And isn’t this a one-to-one relationship, and so not needed?

like image 848
Steven Johnston Avatar asked Mar 06 '16 05:03

Steven Johnston


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 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.

Has one relation in rails?

A has_one association indicates that one other model has a reference to this model. That model can be fetched through this association. This relation can be bi-directional when used in combination with belongs_to on the other model.


1 Answers

Let's use some concrete terms for examples. We'll say a user has one profile.

To generate the user and profile, you could use:

rails generate model User email:string username:string
rails generate model Profile user:references about_me:text

So yes, you do have to add the line has_one :profile to the user model. No, you don't have to add the line belongs_to :user to the profile model as this will be added for you.

As for your last question, I'm not sure what you mean. Yes, this is a one-to-one relationship, but what part do you think is not needed? The has_one :profile line?

If that's the part you're not understanding, you're not fully understanding what this line gives you. It adds useful methods to the User class, most important of which are probably @user.build_profile and @user.profile. Might not seem like much, but pretty cool for adding just one line of code imho.

like image 183
n_i_c_k Avatar answered Oct 22 '22 18:10

n_i_c_k