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.
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.
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 end
class User < ApplocationRecord belongs_to :user end
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" end
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" end
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
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.
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.