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
app/models/user.rb
class User < ApplocationRecord
has_many :posts
end
app/models/user.rb
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.
app/models/user.rb
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.
app/models/user.rb
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.
app/models/user.rb
class User < ApplocationRecord
has_many posts, dependent: :destroy
When the model is related, the reference source data can be retrieved with the following description.
example
@posts = @user.posts
The methods that can be used with has_many can use aggregate methods and query methods.
example
@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.
example
@user.posts.build(name: "taro")
If you write <<, you can even save the record.
example
@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