I am new to Rails, I need to identify a way by which I can update domain of email for all records in the User table.
For instance User table has email column which has @xyz.com domain for all the records in User table. I want to change this domain to a new domain .i.e. @abc.com
I have seen different answers which are using
User.update_all(some_column: "bar")
But it will not work for me. Can anyone please guide me on this. Thanks
CodePudding user response:
A very simple but not very fast solution:
User.find_each { |usr| usr.update(email: usr.email.sub('@xyz.com', '@abc.com')) }
When there are a lot of users without a '@xyz.com' email address in the table then your might want to only load matching users in the first place:
User
.where("email LIKE '%@xyz.com'")
.find_each { |usr| usr.update(email: usr.email.sub('@xyz.com', '@abc.com')) }
The fastest solution would certainly be to update the records in pure SQL but the syntax might depend on the database engine you are using. And when your table is not too big (hundreds of thousands of records) it is probably not worth it to not use Rails.