0

I have a saved model and want to use the attributes of this model to fill a new one.

b = Model.new model.attributes

WARNING: Can't mass-assign protected attributes for Model: id, created_at, updated_at

I do not want to give warning to attribute id

4 Answers4

1

Why not duplicate the record? This will give you a new Id but wont keep associations. Refer to this answer.

new_record = old_record.dup

GL & HF.

Community
  • 1
  • 1
rlecaro2
  • 755
  • 7
  • 14
0

If you use create! instead of new, it will instantiate an object and save it without the callbacks.

attrs = Model.last.attributes
new_model = Model.create!(attrs)
nickcoxdotme
  • 6,567
  • 9
  • 46
  • 72
0

If you want to get rid of the warning use except on the attributes hash to get rid of the unwanted attributes:

b = Model.new model.attributes.except(:id, :created_at, :updated_at)

That should remove those attributes from the hash before passing them into Model.new

DiegoSalazar
  • 13,361
  • 2
  • 38
  • 55
0

To copy an ActiveRecord object you should use dup (http://api.rubyonrails.org/classes/ActiveRecord/Core.html#method-i-dup). This will copy your source object except the id and created_at, updated_at type attributes to a new record which you can save when you want to.

Coenwulf
  • 1,937
  • 2
  • 15
  • 23