我有以下两个模型:
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
然后在我的控制器中:
@activity = Activity.find(params[:id])
@activity.completed_date = Time.now
@activity.process.update_status!
如果我在这一行之后直接放置一个调试器,并打印出@activity.completed 它返回true,但是@artifact.status 仍然是“not_started”(假设没有其他活动)。
但是,如果我在更新之前添加以下行:
@activity.process.activities[@activity.process.activities.index(@activity)] = @activity
状态已正确更新。
为什么@activity 的更改不会传播到 process.activities?我怎样才能让它传播?