ruby-on-rails – 嵌套属性可以与继承结合使用吗?

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 嵌套属性可以与继承结合使用吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下课程:

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

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

  1. has_and_belongs_to_many :people
  2. accepts_nested_attributes_for :people

当然还有Person类中的相应语句.如何通过nested_attributes方法将Developer添加到项目中?以下不起作用:

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

如您所见,类型属性设置为nil而不是“Developer”.

解决方法

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

Rails 2.3

  1. class Person < ActiveRecord::Base
  2.  
  3. private
  4. def attributes_protected_by_default
  5. super - [self.class.inheritance_column]
  6. end
  7. end

Rails 3

请参阅@tokland建议的solution.

警告:

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

参考:

SO Question on the topic

猜你在找的Ruby相关文章