在DataMapper中销毁“has n,:things,:through => Resource”关联

时间:2012-01-24 15:30:36

标签: ruby ruby-datamapper

我有一个名为MySet的集合类:

class MySet
  include DataMapper::Resource

  property :id, Serial
  has n, :my_elements, :through => Resource

  def add integer
    unless my_elements.first(:integer => integer)
      my_element = MyElement.create :integer => integer
      my_elements << my_element
      my_elements.save
    end
    self
  end

  def has_integer? integer
    !my_elements.first(:integer => integer).nil?
  end

  def delete integer
    if has_integer? integer
      my_elements.first(:integer => integer).destroy
      my_elements.save
    end
    self
  end

  def size
    my_elements.size
  end
end

和一个名为MyElement的元素类:

class MyElement
  include DataMapper::Resource

  property :id, Serial
  property :integer, Integer
end

我希望能够在MySet中添加和删除元素。但是,以下规范:

describe MySet do
  subject do
    MySet.create
  end

  it "adds and deletes" do
    subject.add 1
    subject.delete 1
    subject.size.should == 0
  end
end

失败了:

Failure/Error: subject.size.should == 0
expected: 0
got: 1 (using ==)

这类似于DataMapper has n through Resource DELETE (Remove from association) not working中描述的问题,除了MyElement未指定与MySet的关联。但是,我认为该帖子中的解决方案就是我正在使用的解决方案,它似乎无法正常工作。

1 个答案:

答案 0 :(得分:0)

查看收集文档:

http://rubydoc.info/github/datamapper/dm-core/master/DataMapper/Collection

http://rubydoc.info/github/datamapper/dm-core/master/DataMapper/Associations/ManyToMany/Collection

我认为你所做的一些事情是无关紧要的,MyElement.create应该是MyElement.first_or_create但更重要的是,你摧毁其中一个MyElement的部分并不完全正确。看起来你要做的就是从“my_elements”集合中删除它,所以你应该找到它,然后从集合中“删除”它:

def delete integer
  element = my_elements.first(:integer => integer)
  my_elements.delete(element)
  self
end

(摧毁它也可能是你想要做的事情的一部分,你可以单独做到这一点。)

就像你正在做的那样摧毁它可能实际上有效(我不确定),但你可能不得不在测试中重新加载资源以查看更新的大小:

subject.reload
subject.size.should == 0