I have a jobs
table and a activities
table. A Job can have multiple Activities. The relationship is polymorphic.
Tables:
job activities
----------- -------------
id id
... target_id
target_type
...
Model classes:
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 will bring all Jobs that are in a certain state, considering Rails 3/4 ActiveRecord?
I also came up with an idea, instead of doing this query, to use something like the "counter caches" make and denormalize that relationship. I would create a redundant field calledstate
in the Job
model and keep the two in sync using a after_create
in the Activity
model. Something like this:
after_create :update_state
def update_state
target.update_attribute(state: self.state) if target.respond_to?(:state)
end
Would this be a viable alternative?