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
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
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.
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)
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
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.