How can I set a timestamp field with the "update" or "update_all" methods of ActiveRecord?
This is a Rails 3 project.
I just can't figure out how to do this. I have two columns:
last_migrated timestamp
migration_message text
that I would like to update, with condition:
:subdomain => "someval"
and yet everything I have tried has failed. I have tried about every MyModel.update and MyModel.update_all variation I can think of. The documentation just is not penetrating my thick sku开发者_开发技巧ll for some reason. Please help.
To clarify, I want to use an AR method to do the following:
update brands
set last_migrated = x,
migration_message = y
where subdomain = 'someval'
You can just use the where
method like this:
Brand.where(:subdomain => 'someval').update_all(:last_migrated => Time.now, :migration_message => 'Some message')
I ended up doing:
ActiveRecord::Base.connection.execute("update brands set migration_status = 'COMPLETE', migration_message = '', last_migrated = sysdate() where subdomain = '#{self.subdomain}'")
which isn't the best way to do it in AR, and it isn't the Rails Way, but the other things I tried in AR did not behave (update_all), so at least this works.
And since no one could answer my question (thanks for trying amit), and this works, then it will remain the answer until someone can offer a better one.
The question is not clear, but if you are trying to update the attributes of the model then use:
ModelName.update_attributes!(:migration_message => "The message", :last_migrated => the_timestamp) if ModelName.subdomain == "someval"
where the_timestamp is a DateTime object or Date object depending on how you have defined it in the migration.
For update_all usage:
ModelName.where(<condition>).update_all(:migration_message => "The message", :last_migrated => Time.now)
精彩评论