通常会通过其父对象构建相关的模型实例:
@child = @parent.children.build(params[:child])
但是当我们使用STI并且我们想要这样做同时将其构建为子类之一时,语法似乎就会崩溃。据我所知,这是最好的方法(忽略不根据批准的列表检查类型的安全问题):
@child = params[:type].classify.constantize.new(params[params[:type]])
@child.parent = @parent
这是最好的方法吗?我正在使用单个控制器来构建所有不同的子类类型,因此我需要将类型作为参数提供。
答案 0 :(得分:0)
我通常使用这个技巧:
class BaseModel < ActiveRecord::Base
private
# this will enable you to set the type field
def attributes_protected_by_default
super - [self.class.inheritance_column]
end
end
现在在您的控制器中:
@parent.children.build(params[:base_model])
确保params [:base_model]哈希有一个名为type
的字段。我通常会添加一个隐藏的表单字段来存储类型。
确保添加相关检查以确保创建正确的子类型。
注意:这个技巧在Rails 3中不起作用。