Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Rails update_all method to update fields with value from another column

I'm trying to update a field in using update_all. However I need the value to be taken from another field which is re-written to my specific format.

If I have something like this in my model:

 def self.clean_mac_address()
   clean_mac_address = :macaddress.gsub(/[^0-9a-z]/i, '')
 end

When I run this:

 Radacct.update_all("mac_clean = #{clean_mac_address}")

I get an error:

 NoMethodError: undefined method `gsub' for :macaddress:Symbol

Any thoughts how I can do this? Or is there a simpler way to update the field?

like image 922
simonmorley Avatar asked Feb 01 '12 08:02

simonmorley


1 Answers

update_all generates a single SQL query to run - it can't do clever stuff like change arbitrary bits of ruby into equivalent SQL.

You either need to load all you instances (via find_each for example) and fix them one by one (ie don't use update_all), for example

Foo.find_each do |foo|
  # update foo here
  foo.save!
end      

Or find a way of expressing that cleaning operation in SQL. For example Postgres has a regexp_replace function

Foo.update_all("some_column = regexp_replace(some_column, 'your_regexp_here', '','g')")

Which would remove everything replacing that regexp. Obviously you'll need to check the documentation for your database to see whether it supports such a feature.

like image 166
Frederick Cheung Avatar answered Sep 23 '22 15:09

Frederick Cheung