Association (1 to 1)! !!

association?

To briefly explain, it is the association between tables using a model. Associate the tables with each other and change from one model to the other It's to make it accessible.

Reasons for associating

In Rails, there are two "associations" It's the connection between Active Record models.

You need to make an association between the two models, Do you know the reason?

That's right, by associating, the common operation of the code becomes more It's simple and easy to do.

Method used when defining an association (1 to 1)

has_one method

** Used when the association is one-to-one. ** ** ** As a caveat, write "has_one" on the parent model side. Write "belongs_to" on the child model side. ** **

The "belongs_to" method is explained at the following URL. Please refer to that. I will omit the explanation this time. </ font>

belongs_to method reference article

The summary is as follows.

has_one.png

In explaining this time, a description example with the following association (relationship) I will put it.

user and address one-to-one

Association definition description method

First, I will put a description example of ** User model **.

/models/user.rb

class User < ApplicationRecord

   has_one :address
end

As for how to write, has_one: model name (singular) ** This time, the model name is singular because it is "1 to 1". </ font> **

This concludes the description of the User model.

Next, let's go to the description of ** address model **.

/models/address.rb

class Address < ApplicationRecord

  belongs_to :user

end

The way to write it is belong_to: model name (singular).

You now have an association between the User model and the address model.

Summary

** Use has_one for "one-to-one" associations! !! When describing "one-to-one", use "one-to-many", "many-to-many", etc. The model name is written in the singular rather than the plural, so you don't have to be careful. It's okay lol **

So far, I have explained "one-to-one" and "one-to-many", so the rest It will be "many-to-many".

*** I hope you can understand how to define a "one-to-one" association. Thank you for visiting. *** ***

that's all.

Recommended Posts