Ruby on rails rails模型模板(或实例继承)选项?
我想在rails中创建“参数化”模型;例如,我想定义Ruby on rails rails模型模板(或实例继承)选项?,ruby-on-rails,inheritance,prototype,Ruby On Rails,Inheritance,Prototype,我想在rails中创建“参数化”模型;例如,我想定义原型配方,然后能够制作多个派生配方;也许一个衍生配方使用更多的糖,另一个使用更少的鸡蛋或其他东西。关键点是,我希望所有“派生”实例从单个共享的PrototypeRecipe继承属性,但能够进行局部修改 理想情况下,我希望能够在原型上定义方法(比如,组合一个购物列表),并让这些方法响应派生实例中的局部更改(因此,如果我指定3个鸡蛋而不是2个鸡蛋,我可以调用原型的make_shopping_list函数,它会反映这一点) 有没有一种现有的方法来完成
原型配方
,然后能够制作多个派生配方
;也许一个衍生配方使用更多的糖,另一个使用更少的鸡蛋或其他东西。关键点是,我希望所有“派生”实例从单个共享的PrototypeRecipe
继承属性,但能够进行局部修改
理想情况下,我希望能够在原型上定义方法(比如,组合一个购物列表),并让这些方法响应派生实例中的局部更改(因此,如果我指定3个鸡蛋而不是2个鸡蛋,我可以调用原型的make_shopping_list
函数,它会反映这一点)
有没有一种现有的方法来完成这样的事情?以下是迄今为止我能想到的最好的:
class Ingredient << ActiveRecord::Base
belongs_to :recipe, :polymorphic => true
# uuid => UUID String (for grouping ingredients which change between prototype and derived instances)
end
class PrototypeRecipe << ActiveRecord::Base
has_many :ingredients
def make_ingredient_list(derived_recipe = nil)
self.ingredients.map {|i| derived_recipe.nil? ? i : derived_recipe.ingredients.where(:ingredient_uuid => i.uuid).first }
end
end
class DerivedRecipe << ActiveRecord::Base
belongs_to :prototype_recipe
has_many :ingredients
def method_missing(sym, *args)
self.prototype_recipe.send( sym, *args, self)
end
end
类成分为true
#uuid=>uuid字符串(用于在原型和派生实例之间更改的分组成分)
结束
类PrototypeRecipe i.uuid).first}
结束
结束
class-DerivedRecipe我不是100%了解您希望有什么行为,所以这里是我尝试的解决方案
单表继承(STI)。您的基类将是PrototypeRecipe
,您的子类将是DerivedRecipe
在prototype\u recipes
表中,指定type
列(文本)。这会向想要使用STI的Rails发送信号。如果将make\u components\u list
方法放在基类中,则可以从子类访问它
# app/models/ingredient.rb
class Ingredient < ActiveRecord::Base
belongs_to :recipe, :class_name => "PrototypeRecipe"
...
end
# app/models/prototype_recipe.rb
class PrototypeRecipe < ActiveRecord::Base
has_many :ingredients
has_many :derived_recipes
def make_ingredient_list
...
end
end
# app/models/derived_recipe.rb
class DerivedRecipe < PrototypeRecipe
belongs_to :prototype_recipe
end
这就是你要找的吗
@cupcakes = PrototypeRecipe.create
@cupcakes_with_extra_eggs = @cupcakes.derived_recipes.create
print @cupcakes_with_extra_eggs.make_ingredient_list