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我的问题是:这有可能吗?还是有别的办法可以让我这么做?
发布于 2011-12-11 15:17:46
可以使用clone方法克隆对象。更多信息来自红宝石医生。
如果要克隆所需的对象,则克隆将包含相同的信息,但object_id将有所不同。
发布于 2011-12-11 15:20:56
我认为,你需要创建另一个模型
class RecipeIngredients < ActiveRecord::Base
belongs_to :recipe
belongs_to :ingredient
attr_accessible :in_stock
end希望这能回答你的问题。
https://stackoverflow.com/questions/8465024
复制相似问题