2011-12-11 25 views
0

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 

我的問題:這是可能的嗎?還是有其他方法可以做到這一點?

+2

在rspec中,你可以這樣寫:'tomato_for_pizza.should_not be tomato_for_spaghetti' – apneadiving

+0

啊謝謝 – axsuul

回答

0

您可以使用clone方法克隆一個對象。更多在ruby-doc.

如果將克隆所需對象的副本將包含相同的信息,但OBJECT_ID會有所不同

+0

是的,但是如何在通過ActiveRecord急切加載時克隆它們? – axsuul

+0

對於rails 3.1,你應該使用dup而不是克隆 - 據說這似乎很奇怪,你會有一個'番茄'的實體(成分)在哪裏in_stock根據其與食譜的關係而不同? in_stock如何不從數據庫中確定? 'tomato_for_pizza = pizza.ingredients.first.dup tomato_for_spaghetti = spaghetti.ingredients.first.dup' – house9

0

我想,你需要創建另一個模型

class RecipeIngredients < ActiveRecord::Base 
    belongs_to :recipe 
    belongs_to :ingredient 

    attr_accessible :in_stock 
end 

希望這回答你的問題。

+0

謝謝,但是,我並不想在數據庫中堅持'in_stock'屬性 – axsuul

相關問題