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

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

我有以下类(class):

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

  • Project模型我添加了以下语句:
    has_and_belongs_to_many :people
    accepts_nested_attributes_for :people
    

    当然还有类中的适当语句Person .如何添加 DeveloperProject通过 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" .

    最佳答案

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

    class Person < ActiveRecord::Base
    
      private
    
      def self.attributes_protected_by_default
        super - [inheritance_column]
      end
    end
    

    关于ruby-on-rails - 嵌套属性可以与继承结合使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2553931/

    相关文章:

    java - EclipseLink + JPA + 通用实体 + SINGLE_TABLE 继承

    postgresql - 在 PostgreSQL 中使用表继承时获得正确的行

    ruby-on-rails - 带有 Acts_As_Taggable_On 的 Rails 3 中未初始化的标记常量

    ruby-on-rails - Ruby on Rails 脚手架开发插件

    java - 如何重构这个简单的类字段

    html - 在 CSS 中继承类

    ruby-on-rails - 使用searchkick设置高级搜索,处理与多个模型的关联(Rails)

    mysql - 根据 has_many 关系按计数排序

    Java继承之谜

    ruby-on-rails - 使用 STI 查询数据库的效率