爲了討論的目的我做了一個測試有兩個表:刪除habtm關係中的許多重複條目之一?
:stones and :bowls (both created with just timestamps - trivial)
create_table :bowls_stones, :id => false do |t|
t.integer :bowl_id, :null => false
t.integer :stone_id, :null => false
end
該機型是不言自明,而基本的,但在這裏,他們是:現在
class Stone < ActiveRecord::Base
has_and_belongs_to_many :bowls
end
class Bowl < ActiveRecord::Base
has_and_belongs_to_many :stones
end
中,問題是:我希望每個碗裏都有許多相同的石頭。我希望能夠只移除一個,而將其他相同的石頭留在後面。這看起來很基本,我真的希望我都能找到解決方案,而且當我這樣做的時候不會覺得自己太白癡。
這是一個測試運行:
@stone = Stone.new
@stone.save
@bowl = Bowl.new
@bowl.save
#test1 - .delete
5.times do
@bowl.stones << @stone
end
@bowl.stones.count
=> 5
@bowl.stones.delete(@stone)
@bowl.stones.count
=> 0
#removed them all!
#test2 - .delete_at
5.times do
@bowl.stones << @stone
end
@bowl.stones.count
=> 5
index = @bowl.stones.index(@stone)
@bowl.stones.delete_at(index)
@bowl.stones.count
=> 5
#not surprising, I guess... delete_at isn't part of habtm. Fails silently, though.
@bowl.stones.clear
#this is ridiculous, but... let's wipe it all out
5.times do
@bowl.stones << @stone
end
@bowl.stones.count
=> 5
ids = @bowl.stone_ids
index = ids.index(@stone.id)
ids.delete_at(index)
@bowl.stones.clear
ids.each do |id|
@bowl.stones << Stone.find(id)
end
@bowl.stones.count
=> 4
#Is this really the only way?
所以......被吹走了整個事情,從鍵重建它真正的唯一途徑?
哦,不......我想這並不一定如此。我當然認爲你的解決方法...最終,我寧願移動實際的物體而不是保持計數器。愛你的照片。 – 2009-07-08 01:10:01
如果你想這樣做,你也可以使用`StonePlacement.find_by_bowl_and_stone(@bowl,@stone).first.destroy`或類似的東西。 – wombleton 2009-07-08 01:13:32
當然可以......有一箇中間對象來操縱開放各種可能性。那麼,我的問題的答案是否定的? – 2009-07-08 01:48:24