【问题标题】:Rails updating model through associationRails 通过关联更新模型
【发布时间】:2013-08-08 23:38:26
【问题描述】:

我有以下两种型号:

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

【问题讨论】:

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


    【解决方案1】:

    我不将此inverse_of 与 has_many 一起使用。见这篇文章:ActiveRecord :inverse_of does not work on has_many :through on the join model on create

    这是来自RailsGuides 的相关简介:

    inverse_of 支持有一些限制:

    它们不适用于 :through 关联。他们不与 :多态关联。它们不适用于 :as 关联。为了 belongs_to 关联,has_many 反向关联被忽略。

    【讨论】:

    • '对于 belongs_to 关联,has_many 反向关联被忽略' 就是这样。谢谢,很抱歉搞砸了你的分数;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    • 2013-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    相关资源
    最近更新 更多