1

AR でこの種の機能を探していましたが、見つからないようです。AR の Dirty 実装は、直接の属性の 1 つが変更された場合にのみ、既に永続化されたインスタンスがダーティと見なされることを示しています。だから、言ってみましょう:

class Picture < ActiveRecord::Base
  belongs_to :gallery
  has_one :frame
end

この場合、次のようなことができます。

p = Picture.new(:gallery => Gallery.new, :frame => Frame.new)
p.save #=> it will save the three instances
p.gallery = Gallery.new
p.save #=> will not save the new gallery
p.gallery_id_will_change!
p.gallery = Gallery.new
p.save #=> this will save the new Gallery

しかし、Picture 実装はそれを参照する属性を所有していないため、has_one アソシエーションに対して同様のことを行うことはできません。したがって、そのような汚いマークアップは不可能のようです。それともそうではありませんか?

4

2 に答える 2

1

私が理解できる最善のことは次のとおりです。

class Picture < ActiveRecord::Base
  belongs_to :gallery
  has_one :frame

  after_save :force_save_frame

  def force_save_frame
    frame.save! if frame.changed?
  end
end
于 2013-02-15T23:41:14.287 に答える
1

私たちが予想したように、Dirty フラグは、関連するオブジェクトではなく、モデル自体の属性に設定されます。モデルに外部キーがあるため、belongs_to に対してのみ機能します。

しかし、あなたはそのようなトリックを作ることができます

module FrameDirtyStateTracking
  def frame=(frame)
    attribute_will_change!('frame')
    super
  end
end

class Picture < ActiveRecord::Base
  prepend FrameDirtyStateTracking

  belongs_to :gallery
  has_one :frame
end

picture = Picture.new
picture.frame = Frame.new
picture.changed? # => true
picture.changed # => ['frame']
于 2015-09-18T09:29:54.213 に答える