1

通常人们会通过其父对象构建一个相关的模型实例:

@child = @parent.children.build(params[:child])

但是当我们使用 STI 并且我们想要这样做的同时将其构建为子类之一时,语法似乎会崩溃。据我所知,这是最好的方法(忽略不根据批准列表检查类型的安全问题):

@child = params[:type].classify.constantize.new(params[params[:type]])
@child.parent = @parent

这是最好的方法吗?我使用单个控制器来构建所有不同的子类类型,所以我需要提供类型作为参数。

4

1 回答 1

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 中不起作用。

于 2011-03-03T08:41:46.737 回答