Matt Elhotiby
Matt Elhotiby

Reputation: 44086

How do I prepopulate from a previous object in rails?

I have this line of code

Account.build_address

and this works but I need to prepopulate is with a previous address so if i had the params i could do

Account.build_address(params[:address])

But i dont have the params I have a previous address object so for the sake of example i can say

@previous_address = Address.first
Account.build_address(@previous_address)

But I dont think this is in the format i need to prepopulate...any ideas

Upvotes: 0

Views: 93

Answers (2)

klochner
klochner

Reputation: 8125

You don't need to build, you can just clone the existing object:

@previous_address.clone

That will copy all columns of the @previous_address model, except for the id field

Upvotes: 2

Veraticus
Veraticus

Reputation: 16084

Try this:

@previous_address = Address.first
Address.build_address(@address.attributes)

@address.attributes returns a hash of the object's ActiveRecord attributes... so as long as build_address expects a hash, it should generate an object equivalent to the address you pass in.

Upvotes: 1

Related Questions