嵌套属性可以与继承结合使用吗? [英] Can nested attributes be used in combination with inheritance?

查看:182
本文介绍了嵌套属性可以与继承结合使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:


  • 项目


  • > 开发人员

  • > 经理

  • Project
  • Person
  • Person > Developer
  • Person > Manager

项目中 model我添加了以下语句:

In the Project model I have added the following statements:

has_and_belongs_to_many :people
accepts_nested_attributes_for :people

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

And of course the appropriate statements in the class Person. How can I add a Developer to a Project through the nested_attributes method? The following does not work:

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

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

As you can see the type attributes is set to nil instead of "Developer".

推荐答案

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

I encountered a similar problem few days ago. The inheritance column(i.e. type) in a STI model is a protected attribute. Do the following to override the default protection in your Person class.

Rails 2.3

class Person < ActiveRecord::Base

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

Rails 3

请参阅 @tokland 解决方案 >。

Refer to the solution suggested by @tokland.

警告:

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

You are overriding the system protected attribute.

参考:

SO关于该主题的问题

这篇关于嵌套属性可以与继承结合使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆