Rails通过关联更新模型

时间:2013-08-08 23:38:27

标签: ruby-on-rails-3 rails-activerecord model-associations

我有以下两种模式:

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?我怎样才能让它传播?

1 个答案:

答案 0 :(得分:3)

我不认为inverse_of适用于has_many。请参阅此文章:ActiveRecord :inverse_of does not work on has_many :through on the join model on create

以下是RailsGuides的相关模糊:

  

inverse_of支持有一些限制:

     

它们不适用于:通过关联。他们不合作   :多态关联。它们不适用于:作为协会。对于   belongs_to association,has_many反向关联被忽略。