[RUBY] Model association in Rails


I think that the association between models will be the basis of the basics in creating an application, so I will summarize it with the meaning of review.

What is an association?

Associations between models are associations between database tables using foreign keys. By doing this, it is very convenient to call up the necessary data with a simple description, or to delete the related data at the same time when deleting the data.

One-to-many association

A typical association seems to be a one-to-many association. One-to-many association is the association of one record in one table with multiple records in another table. Example: Associate the User model with the Post model


class User < ApplocationRecord
  has_many :posts


class User < ApplocationRecord
  belongs_to :user

Using the has_many method means "has a lot of", and using the belongs_to method means "belonging to", and the two models are related. In the above case, it means something like "User has a lot of Posts".

These methods have a naming convention: the has_many method uses the model name in the plural, and the belongs_to method uses the model name in the singular. Also, specify the column name of the foreign key as the referenced model name (singular) + \ _id. (Example: user \ _id) If you specify a foreign key, specify foreign_key as an option.


class User < ApplocationRecord
  has_many posts, foreign_key: "client_id"

Specify the class_name option to change the method name. After has_many, change it to a new method name and specify the original model name in class_name.


class User < ApplocationRecord
  has_many tweets, class_name: "Post"

If you specify the dependent option for has_many and specify: destroy, the referenced record is automatically deleted when the referenced record is deleted.


class User < ApplocationRecord
  has_many posts, dependent: :destroy

What you can do with association

When the model is related, the reference source data can be retrieved with the following description.


@posts = @user.posts

The methods that can be used with has_many can use aggregate methods and query methods.


@posts = @user.posts.count
@posts = @user.posts.order("")

If you want to set the data to be associated with the reference, you can use the build method to associate it. You can also specify model attributes as arguments.


@user.posts.build(name: "taro")

If you write <<, you can even save the record.


@user.posts << @post


I was able to reconfirm the association between the models, including the meaning of a review. It's still a basic part, and there are one-to-one and many-to-many associations, so I'd like to summarize it on another occasion.

Recommended Posts

Model association in Rails
[Rails] Model Association (Association)
Group_by in Rails
Adding columns in Rails
Disable turbolinks in Rails
CSRF measures in Rails
^, $ in Rails regular expression
Use images in Rails
Understand migration in rails
Ruby On Rails Association
Split routes.rb in Rails6
Implement markdown in Rails
Migration error after Activerecord association in Rails5 + Docker environment
Get UserAgent in [Rails] controller
Implement application function in Rails
Declarative transaction in Rails #ginzarb
Implement follow function in Rails
Japaneseize using i18n with Rails
rails g model Overall flow
Implement LTI authentication in Rails
About naming Rails model methods
Error in rails db: migrate
Gem often used in Rails
Display Flash messages in Rails
View monthly calendar in Rails
[Rails] Japaneseize model attribute names
Implement import process in Rails
Use multiple checkboxes in Rails6!
Rewrite Routes in Rails Engine
Rails: Capture regular expressions in emails!
[Rails] Keyword search in multiple tables
[Rails] Session timeout setting in devise
Enable jQuery and Bootstrap in Rails 6 (Rails 6)
[Rails] How to write in Japanese
[Rails] Unexpected validation error in devise
About the symbol <%%> in Rails erb
[Rails] Use cookies in API mode
Implement simple login function in Rails
Create a new app in Rails
Ruby on Rails Japanese-English support i18n
Rails model and table naming conventions
[Solution] Webpacker :: Manifest :: MissingEntryError in Rails
Implement a contact form in Rails
Remove "assets" and "turbolinks" in "Rails6".
CRUD features and MVC in Rails
How to introduce jQuery in Rails 6
How to rename a model with foreign key constraints in Rails
First pagination feature added in rails
Data is not registered in Rails.
[Rails 6] Customize Bootstrap in Rails + Bootstrap 5.0.0-alpha environment
Implement CSV download function in Rails
Password dummy data generation notes in Rails model unit test code
Ruby methods often used in Rails
How to install Swiper in Rails
How to debug the processing in the Ruby on Rails model only on the console
How to implement search functionality in Rails
Definitions other than 7 basic actions in Rails
[Rails] Function restrictions in devise (login / logout)
How to change app name in rails
[Rails] Unit test code for User model
How to use custom helpers in rails