Duplicating ActiveRecord in Rails, the problem of creating a new object using existing parameters

I am trying to duplicate a resource in Rails in my application and have encountered some problems.

Customization: I have a library of “element templates” that the user can use, and then modify the resulting element. I now have this setting:

@temp_item = @template_item.dup
@new_item = @user.items.create(@temp_item.attributes)

However, I ran into a problem when it tries to copy through protected attributes as well (namely created_at and updated_at). I would prefer not to list each attribute separately, so my question is: is there a way to exclude attributes that are copied in this instance?

Thank.

+3
source share
3 answers

Mischa .

@temp_item_attributes = @template_item.attributes.reject{ |k,v|
  %w(created_at updated_at).include?(k)
}
@new_item = @user.items.create(@temp_item_attributes)
+7

Mark reject, case/when :

@template_item.attributes.reject{ |k,v| %w(created_at updated_at).include?(k) }
+4

It seems to me that you should make a combination of the answers of Mark Payne and Misha, namely:

temp_item_attributes = @template_item.attributes.reject do |k,v|
  %w(created_at updated_at).include?(k)
end
@new_item = @user.items.create(temp_item_attributes)

I cannot believe that there is no convenient method for this behavior; I did not look too hard, but did not find him.

+2
source

All Articles