追加后保存回调未运行

时间:2013-04-25 19:11:26

标签: ruby datamapper

我在尝试使用<<运算符追加关系时遇到问题。如果我在追加后保存,我的回调似乎没有运行。

我有两种模式:

织物

class Fabric
  include DataMapper::Resource

  property :id,           Serial
  property :name,         String
  property :fixed_color,  Boolean
  property :active,       Boolean, :default => true

  has 1,      :cut
  has n,      :colors, :through => Resource

  after :save, :add_to_fishbowl

  def add_to_fishbowl
    puts self.colors.size
  end
end

颜色

class Color
  include DataMapper::Resource

  property :id,   Serial
  property :name, String

  has n,      :cut
  has n,      :fabrics, :through => Resource
end

我创造了两种颜色和一种面料:

yellow = Color.new(:name => "yellow")
red = Color.new(:name => "red")

f = Fabric.create(:name => "tricot", :fixed_color => false)

如果我使用了append运算符,则不会运行我的回调:

f.colors << red
f.save
f.colors << yellow
f.save
puts f.colors.size
=> 0
=> 2

如果我添加数组,则为:

f.colors = f.colors + [red]
f.save
f.colors = f.colors + [yellow]
f.save
puts f.colors.size
=> 0
=> 1
=> 2
=> 2

我正在运行ruby 1.9.3p392和data_mapper(1.2.0)。

1 个答案:

答案 0 :(得分:0)

你错过了关系,有n,:cut

class Color
  include DataMapper::Resource

  property :id,   Serial
  property :name, String

  has n,      :cuts
  has n,      :fabrics, :through => Resource
end