Jeeho Lee
Posted on February 21, 2024
The create method when called on a model creates and saves an ActiveRecord instance object with the attributes that you specified populated.
The method can also be attached on an ActiveRecord Relation which would create an ActiveRecord instance object with the attributes you specified populated, but also any scoped attributes from the relation.
For example, if I were to have a relation generated from the following query on a database called Movies to find instances that have a director_id of 1:
movies = Movie.where({ director_id: 1 })
and then I were to apply the create method on that relation with some attributes filled out:
movies.create(title: "New Title")
The generated ActiveRecord instance would have the title attribute populated but also have the director_id attribute populated with 1 which it took from the relation's attribute scoping. The create method also makes database changes so there is no need to call .save afterwards either.
This will be helpful to remember since it could potentially mean not having to specify attributes manually.
Posted on February 21, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024