Today I Learned

A Hashrocket project

Creating an object from an ActiveRecord::Relation

Rails allows us devs to create a record from an ActiveRecord::Association like so:

> wheel = Car.find_by(type: 'Mazda').wheels.build
> wheel.car_id
1

And in this way we can create a wheel associated with a specific car.

But we can also create an object from an ActiveRecord::Relation that allows us to predefine attributes.

> spare_wheel = car.wheels.where(spare: true).build
> spare_wheel.spare
true
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.