为什么has_many通过触摸:真正的工作是这样的自我参照模型?

时间:2014-05-05 05:48:18

标签: ruby-on-rails activemodel

我有一个自我引用的关系和一个has_many_through关联设置了一个名为" Item"的模型。我在"加入模型"上使用了触控功能。 我的问题是,当我"标记"一个孩子的对象,父母没有被触及"即使有一个触摸"链"在我看来应该更新父母。

# the model

class Item < ActiveRecord::Base
  belongs_to :parent_item, class_name: 'Item', touch: true, inverse_of: :children_items
  has_many :children_items, class_name: 'Item', inverse_of: :parent_item
  has_many :taggings, inverse_of: :item
  has_many :tags, through: :taggings
end

class Tagging < ActiveRecord::Base
  belongs_to :tag, inverse_of: :taggings, touch: true
  belongs_to :item, inverse_of: :taggings, touch: true
end

class Tag < ActiveRecord::Base
  has_many :taggings, inverse_of: :tag
  has_many :items, through: :taggings
end


# the behaviour

item = Item.create!
child_item = item.children_items << Item.new

# before tagging
before_tagging_time = item.updated_at
# tagging the child
child_item.tags << Tag.new(name: "unimportant")

# after tagging
item.updated_at == before_tagging_time # => true

这是一个错误吗?

我希望最后一行评估为false,但它的计算结果为true。也就是说,我希望在子项目中添加一个标签,其中标签和项目都触及所有belongs_to关系以触发该模型上的触摸,但它似乎不会以这种方式运行。 / p>

这是我不了解此功能的预期行为的情况吗?我应该使用after_touch回调吗?

我的预期行为是触摸计为保存...我是否需要手动添加&#34; after_touch&#34;回调我的每个模型触摸,这样我就可以获得&#34;触摸链的预期行为&#34;?

1 个答案:

答案 0 :(得分:1)

您的&#34;触及链#34;应该管用。重新加载Item记录,您应该看到updated_at的正确值。

item.reload.updated_at == before_tagging_time # => false