0

I'm having a problem trying to append a relationship using the << operator. If I save after the append, my callback does not seem to run.

I have two models:

Fabric

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

Color

class Color
  include DataMapper::Resource

  property :id,   Serial
  property :name, String

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

I create two colors and a fabric:

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

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

If I used the append operator, my callback is not run:

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

If I add arrays, it is:

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

I'm running ruby 1.9.3p392 and data_mapper (1.2.0).

Anthony DeSimone
  • 1,994
  • 1
  • 12
  • 21

1 Answers1

0

You missing relations, has n, :cuts

class Color
  include DataMapper::Resource

  property :id,   Serial
  property :name, String

  has n,      :cuts
  has n,      :fabrics, :through => Resource
end
Pravin Mishra
  • 8,298
  • 4
  • 36
  • 49
  • Care to elaborate on that? Are you saying that the model is missing? (which it isn't; I excluded it for the post) Or that I need to added one or more cuts to my color in order for this to work correctly? Why would that produce this sort of behavior? – Anthony DeSimone Apr 25 '13 at 20:54