Simon
Simon

Reputation: 128

How to create a new record using the values from a variable already under the same class

I remove records all the time to test, and need to re-create the same record to test again.

So doing this:

User.create(name: "Peter", col1: "etc", col2: "etc", ...)
u = User.last
User.last.delete

How to accomplish something like this?:

User.create(u)

u is already an instance of User class`:

u.class => User(id: integer, name: string, ...)

Upvotes: 0

Views: 61

Answers (3)

SANJAY
SANJAY

Reputation: 21

if you use this : User.create!(u.attributes)

it will give you error ' ActiveRecord::RecordNotUnique '

You can use this. It will create new record with new id

User.create(u.attributes.except('id'))

Upvotes: -1

Andrey Deineko
Andrey Deineko

Reputation: 52357

How to accomplish something like this?:

User.create(u)

create accepts the hash, so you can pass the hash key-value pairs of all u attributes (except for id):

User.create(u.attributes.except('id'))

Note, that it will fail if you have any uniqueness validation.

Upvotes: 3

Simon
Simon

Reputation: 128

Turned out to be as simple as:

User.create!(u.attributes)

Upvotes: 0

Related Questions