Rails 3.1。這裏是我的模型如何保持ActiveRecord對象使用相同的ID分開內存
class Cookbook
has_many :recipes, :include => :ingredients
end
class Recipe
belongs_to :cookbook
has_many :ingredients
end
class Ingredient
belongs_to :recipe
end
而且我有這個數據
Cookbook (id: 1)
Recipe "Pizza" (id: 1)
Ingredient "Tomato" (id: 1)
Ingredient "Cheese" (id: 2)
Recipe "Spaghetti" (id: 2)
Ingredient "Tomato" (id: 1)
Ingredient "Pasta" (id: 3)
現在讓我們來加載數據的ActiveRecord對象
# Eager load all recipes and ingredients
cookbook = Cookbook.includes(:recipes).find(1)
pizza = cookbook.recipes[0]
tomato_for_pizza = pizza.ingredients.first
spaghetti = cookbook.recipes[1]
tomato_for_spaghetti = spaghetti.ingredients.first
不過,我想設置一個標誌上一個的ActiveRecord對象,但不希望它影響具有相同ID的另一個ActiveRecord對象。
tomato_for_pizza.in_stock = true
tomato_for_spaghetti.in_stock # true, but should be false (default)
換句話說,我想Ingredient
對象(即使它們都具有相同的ID和表示在數據庫中的相同的數據)被加載在內存中單獨的對象。在RSpec的語言
tomato_for_pizza.object_id.should_not == tomato_for_spaghetti.object_id
我的問題:這是可能的嗎?還是有其他方法可以做到這一點?
在rspec中,你可以這樣寫:'tomato_for_pizza.should_not be tomato_for_spaghetti' – apneadiving
啊謝謝 – axsuul