0
I have a table jobs
and a table activities
. A Job can have several Activities. The relationship is polymorphic.
Tables:
job activities
----------- -------------
id id
... target_id
target_type
...
Classes of models:
class Job < ActiveRecord::Base
# ...
has_many :activities, :as => :target, :dependent => :delete_all
# ...
end
class Activity < ActiveRecord::Base
# ...
belongs_to :target, :polymorphic => true
# ...
end
The state of a given Job is equal to the state of the last Activity created for Job.
Job +-> Activity 1 - state: new |
+-> Activity 2 - state: submitted +--> Estado desse Job é approved
`-> Activity 3 - state: approved |
What is the best way to do a query that brings all Jobs that are in a given state, considering Rails Activerecord 3/4?
It also occurred to me now an idea to, instead of doing this query, use something like "counter caches" do and denormalize this relationship. I would create a redundancy field called state
on the model Job
and would keep the two in sync using a after_create
on the model Activity
. Something like that:
after_create :update_state
def update_state
target.update_attribute(state: self.state) if target.respond_to?(:state)
end
That would be a viable alternative?