Rails ActiveRecord: create_with, where for new records
More 'things I forgot' - using create_with and where in making new records. We can make use of the resulting association to create new records that match our previous parameters.
Photo by Mark Fletcher-Brown on Unsplash
Using `where` for record creation
We all know that you can use `where` to search for a record:
> purchases = Purchase.where(item_name: "Aerodynamic Copper Watch")
Purchase Load (1.0ms) SELECT "purchases".* FROM "purchases" WHERE "purchases"."item_name" = ? [["item_name", "Aerodynamic Copper Watch"]]
=>
[#<Purchase:0x000000011348e270
But did you know that you can also use the resulting association to create a new record/object with the searched-for values filled in!
Looks something like this:
> purchases = Purchase.where(item_name: "Awesome Socket Wrench")
Purchase Load (0.2ms) SELECT "purchases".* FROM "purchases" WHERE "purchases"."item_name" = ? [["item_name", "Awesome Socket Wrench"]]
=> []
irb(main):019:0> purchases.new
=>
#<Purchase:0x0000000113314318
id: nil,
item_name: "Awesome Socket Wrench",
quantity: nil,
purchase_amount: nil,
purchased_at: nil,
status: nil,
customer_id: nil,
created_at: nil,
updated_at: nil,
description: nil>
That `[]` that returns from the `where` call may look like an empty array, but it is actually an empty Association.
> purchases = Purchase.where(item_name: "Awesome Socket Wrench")
Purchase Load (0.9ms) SELECT "purchases".* FROM "purchases" WHERE "purchases"."item_name" = ? [["item_name", "Awesome Socket Wrench"]]
=> []
irb(main):021:0> purchases.class.name
=> "ActiveRecord::Relation"
That’s why we can do `new` and it will create us a record!
Adding more attributes with `create_with`
When you have that association, you can also create more records - with new or different attributes - by using `create_with`
irb(main):025:0> purchases = Purchase.where(item_name: "Awesome Socket Wrench")
Purchase Load (1.8ms) SELECT "purchases".* FROM "purchases" WHERE "purchases"."item_name" = ? [["item_name", "Awesome Socket Wrench"]]
=> []
irb(main):026:0> purchases.create_with(quantity: 1).new
=>
#<Purchase:0x0000000112ac0f40
id: nil,
item_name: "Awesome Socket Wrench",
quantity: 1,
purchase_amount: nil,
purchased_at: nil,
status: nil,
customer_id: nil,
created_at: nil,
updated_at: nil,
description: nil>
Now, you know I like to focus on practical, real-world uses for language features. I have to admit that right now I can’t think why you would use this over the other options available, but if you can, drop me a note and I can include it in a future posting!
Don’t forget to check out my videos over on my YouTube channel. I do (often lengthy!) tutorials on Real World Rails applications.