Reputation: 15471
I have the following two models:
class Process < ActiveRecord::Base
has_many :activities, inverse_of: :artifact, dependent: :destroy
attr_accessible :name, :activities_attributes
def update_status!
if self.activities.all? {|a| a.completed? }
self.status = 'completed'
elsif self.activities.any? {|a| a.completed? }
self.status = 'in_progress'
else
self.status = 'not_started'
end
save!
end
end
class Activity < ActiveRecord::Base
belongs_to :process, inverse_of: :activities
attr_accessible :name,:completed_date
scope :completed, where("completed_date is not null")
end
Then in my Controller:
@activity = Activity.find(params[:id])
@activity.completed_date = Time.now
@activity.process.update_status!
If I put a debugger directly after this line, and print out @activity.completed it returns true, however @artifact.status is still "not_started" (assume no other activities).
However, if I add the following line before the update:
@activity.process.activities[@activity.process.activities.index(@activity)] = @activity
The status is updated correctly.
Why doesn't the change to @activity propagate into process.activities? And how can I make it propagate?
Upvotes: 1
Views: 899
Reputation: 19308
I don't this inverse_of
works with has_many through. See this article: ActiveRecord :inverse_of does not work on has_many :through on the join model on create
Here is the relevant blurb from the RailsGuides:
There are a few limitations to inverse_of support:
They do not work with :through associations. They do not work with :polymorphic associations. They do not work with :as associations. For belongs_to associations, has_many inverse associations are ignored.
Upvotes: 3