27
loading...
This website collects cookies to deliver better user experience
created_at
and updated_at
fields.datetime
columns in the database. Yet in order to conveniently manage such fields, we would need to accompany each of them with a bunch of methods in the model class. The more timestamp fields we want to manage, the more methods we need. As a result, the model gets bigger and bigger.active_record-events
gem comes into play.has_event
macro which adds convenience methods on top of a datetime
field.Task
model with a completed_at
field. Now, let's add the has_event
macro inside the model class:class Task < ActiveRecord::Base
has_event :complete
end
task = Task.create!
task.completed? # => false
task.complete
task.completed? # => true
task.completed_at # => Sun, 20 Dec 2020 16:54:11 UTC +00:00
task.completed?
, task.not_completed?
), record or overwrite a timestamp (task.complete
, task.complete!
), as well as record multiple timestamps at once (Task.complete_all
).Task.completed
, Task.not_completed
).completed_at
column to the tasks
table in our database. In order to do that, we could manually create a migration file, but it's much easier to use a generator provided by the gem:$ rails generate active_record:event task complete
has_event
statement into the corresponding model class.# db/migrate/XXX_add_completed_at_to_tasks.rb
class AddCompletedAtToTasks < ActiveRecord::Migration[6.0]
def change
add_column :tasks, :completed_at, :datetime
end
end
# app/models/task.rb
class Task < ActiveRecord::Base
has_event :complete
end
aasm
, workflow
or statesman
). Another alternative is ActiveRecord::Enum
, which offers similar functionality with a different underlying mechanism.