DEV Community

Jeeho Lee
Jeeho Lee

Posted on

ActiveRecord Relation and create method

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 })
Enter fullscreen mode Exit fullscreen mode

and then I were to apply the create method on that relation with some attributes filled out:

movies.create(title: "New Title")
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)