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

Her*_* D. 7 inheritance ruby-on-rails single-table-inheritance nested-attributes

我有以下课程:

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

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

has_and_belongs_to_many :people
accepts_nested_attributes_for :people
Run Code Online (Sandbox Code Playgroud)

当然还有课堂上适当的陈述Person.如何通过方法添加Developer到a ?以下不起作用:Projectnested_attributes

@p.people_attributes = [{:name => "Epic Beard Man", :type => "Developer"}]
@p.people
=> [#<Person id: nil, name: "Epic Beard Man", type: nil>]
Run Code Online (Sandbox Code Playgroud)

如您所见,type属性设置为nil而不是"Developer".

tok*_*and 7

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

class Person < ActiveRecord::Base

  private

  def self.attributes_protected_by_default
    super - [inheritance_column]
  end
end
Run Code Online (Sandbox Code Playgroud)


Har*_*tty 5

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

Rails 2.3

class Person < ActiveRecord::Base

private
  def attributes_protected_by_default
    super - [self.class.inheritance_column]
  end
end
Run Code Online (Sandbox Code Playgroud)

Rails 3

请参阅@tokland建议的解决方案.

警告:

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

参考:

关于这个主题的问题