Removing Attributes from an ActiveRecord Model

I transfer data between two activerecord connections, I have all my settings for the correct settings, so I can read from the Legacy :: Tablename and Tablename website and paste them into a new table.

The problem I have is my new model does not have all the attributes that are in the old model, so I get an "unknown attribute" when I try to create an entry in the new model through;

legacy_users = Legacy::User.all legacy_users.each do |legacy_user| User.create legacy_user.attributes end 

however, if I try to remove the insult attribute, it still does not work, for example.

 legacy_user.attributes.delete 'some_attribute' 

Can anyone suggest any pointers?

+4
source share
3 answers

This should work in this case:

 legacy_users = Legacy::User.all legacy_users.each do |legacy_user| u = User.new u.attributes.each do |k, v| old_val = legacy_user.send(k) # Get the attr from old user u.send("#{k}=", old_val) # Set it to the new user end end 

You will also not have to be confused with deleting each unused attribute

+1
source

What about attributes.except (: some_attribute)?

+11
source

I am also working on migration, and in my case, I passed the first_or_create block to clone objects. I could not get delete() or except() to work, but for some reason this works:

scrubbed_obj = my_obj.attributes.reject { |k,v| k == 'the_attribute_you_dont_want' }

new_object.attributes = scrubbed_obj

and then the block saves a penalty. Just throwing this answer if someone else is facing similar problems.

0
source

Source: https://habr.com/ru/post/1341860/