如何保持具有相同ID的ActiveRecord对象在内存中分离

时间:2011-12-11 15:13:46

标签: ruby-on-rails ruby-on-rails-3 activerecord

Rails 3.1 。这是我的模特

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 个答案:

答案 0 :(得分:0)

您可以使用clone方法克隆对象。更多ruby-doc.

如果要克隆所需的对象,则克隆将包含相同的信息,但object_id将不同

答案 1 :(得分:0)

我认为,您需要创建另一个模型

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

  attr_accessible :in_stock
end

希望这能回答你的问题。