Inserting default values in tables using rails
Rails automatically inserts values for columns like created_at and updated_at. Can i configure rails in such a way that it updates more columns. For example all my tables have a column called u开发者_开发百科ser holding the currentuser value, can I default rails ti insert user for any database change?
You could try using the before_save function in your model, unless I've misunderstood the question.
before_save :defaults
def defaults
#some stuff to set your defaults
end
Yes, you could use a before_filter in the model, e.g.
before_update :set_value
def set_value
self.value = "hello"
end
You can use ActiveRecord callbacks to trigger logic when changing states, such as before saving an object to the database. The created_at and updated_at columns in automatically updated when either an object is created (before_create), or updated (before_save). You can define your own callbacks using the class methods defined in the ActiveRecord::Callbacks namespace. An example would be
# app/models/example.rb
class Example < ActiveRecord::Base
before_save :do_something
def do_something
self.value = value
end
end
If you are specifically wanting to record the user that created, updated, or deleted a record, you can save some work and use the Userstamps Rails plugin to automatically record the user. This plugin is located at https://github.com/delynn/userstamp
# app/models/example.rb
class Example < ActiveRecord::Base
model_stamper
end
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
include Userstamp
end
You will need to add the userstamps columns onto each of your models on which you want to record user actions.
More information on ActiveRecord callbacks can be found here: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
Information on timestamps can be found here: ActiveRecord timestamps: http://api.rubyonrails.org/classes/ActiveRecord/Timestamp.html
精彩评论