Command to generate c = "a + b" in console, when 1000's of value "a" and "b" added in MySQL manually
I have three columns in my database:
a
= value
b
= value
c
= a + b
User usually enters a
and b
in the form, and the value is stored in the database. c
will be calculated by the model.
In my model:
class Calculate < ActiveRecord::Base
before_validation_on_create :update_c
before_validation_on_update :update_c
def update_c
if !a.blank? && !b.blank?
self.c = a + b
end
end
end
Just a sample code above. So c
is generated everytime the user clicks "Save".
Now, I am an admin, and I populated 1000's of values for a
and b
using phpMyAdmin CSV import:
id=1, a=4, b=7, c=
id=2, a=1, b=6, c=
id=3, a=3, b=2, c=
.
.
.
Milliondollar question:
What is the best way to do it in console or somewhere else, to tell Rails to generate C for all the 1000's of entries?
Thank you!
UPDATE 1:
Actually the c = a + b
is not that simple in my code. Take geocode_address
as c
, address_geo
as a, b
, here is the full code:
def geocode_address
if !address_geo.blank?
geo=Geokit::Geocoders::MultiGeocoder.geocode(address_geo)
errors.add(:address开发者_开发知识库, "Could not Geocode address") if !geo.success
self.lat, self.lng = geo.lat,geo.lng if geo.success
end
end
I would just connect to MySQL directly (or run the SQL through phpMyAdmin) to issue an update statement.
I'm assuming you want to update ALL the records.
UPDATE table SET c = a + b;
That'll do it for you, nice and fast. I'm guessing you know what the table name is, I'm not familiar with Rails. I don't think you need Rails for this one.
Try this:
Calculate.update_all("c = a+b")
精彩评论