嵌套属性可以与继承结合使用吗?

时间:2010-03-31 14:50:45

标签: ruby-on-rails inheritance single-table-inheritance nested-attributes

我有以下课程:

  • 项目
  • > 开发人员
  • > 经理

Project模型中,我添加了以下语句:

has_and_belongs_to_many :people
accepts_nested_attributes_for :people

当然,班级Person中有适当的陈述。如何通过Developer方法向Project添加nested_attributes?以下不起作用:

@p.people_attributes = [{:name => "Epic Beard Man", :type => "Developer"}]
@p.people
=> [#<Person id: nil, name: "Epic Beard Man", type: nil>]

正如您所看到的,type属性设置为nil而不是"Developer"

4 个答案:

答案 0 :(得分:7)

Rails3的解决方案attributes_protected_by_default现在是一个类方法:

class Person < ActiveRecord::Base

  private

  def self.attributes_protected_by_default
    super - [inheritance_column]
  end
end

答案 1 :(得分:5)

前几天我遇到了类似的问题。 STI模型中的继承列(即type)是受保护的属性。执行以下操作以覆盖Person类中的默认保护。

Rails 2.3

class Person < ActiveRecord::Base

private
  def attributes_protected_by_default
    super - [self.class.inheritance_column]
  end
end

Rails 3

请参阅solution建议的@tokland

警告:

您正在覆盖系统保护的属性。

<强>参考:

SO Question on the topic

答案 2 :(得分:4)

上面的补丁对我不起作用,但是这样做了(Rails3):

class ActiveRecord::Reflection::AssociationReflection
  def build_association(*options)
    if options.first.is_a?(Hash) and options.first[:type].presence
      options.first[:type].to_s.constantize.new(*options)
    else
      klass.new(*options)
    end
  end
end

Foo.bars.build(:type =&gt;'Baz')。class == Baz

答案 3 :(得分:0)

对于我们这些使用Mongoid的人,您需要使_type字段可访问:

class Person
  include Mongoid::Document
  attr_accessible :_type
end