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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay