Today I Learned

hashrocket A Hashrocket project

Set Attributes when Creating with .create_with

You can set attributes to be used when creating new records with .create_with:

Author.create_with(name: "Hashrocketeer")
Author.new.name # => "Hashrocketeer"

This can be particularly useful if you're doing a .find_or_create_by and want to set some values only when creating:

Author
  .create_with(post_count: 0)
  .find_or_create_by(name: "Hashrocketeer")

This will find an author with name "Hashrocketeer". If we find an existing Author, we won't change their post_count. If we don't find an existing Author, we'll create one with a post_count of 0.

Read more in the docs

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.