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
Tweet