嵌套属性可以与继承结合使用吗?
我有以下课程:
- 项目
- 人员
- 人员 > 开发人员
- 人员 > Manager
在 Project
模型中,我添加了以下语句:
has_and_belongs_to_many :people
accepts_nested_attributes_for :people
当然,还有 Person
类中的相应语句。如何通过 nested_attributes
方法将 Developer
添加到 Project
?以下内容不起作用:
@p.people_attributes = [{:name => "Epic Beard Man", :type => "Developer"}]
@p.people
=> [#<Person id: nil, name: "Epic Beard Man", type: nil>]
如您所见,type
属性设置为 nil
而不是 "Developer"
。
I have the following classes:
- Project
- Person
- Person > Developer
- Person > Manager
In the Project
model I have added the following statements:
has_and_belongs_to_many :people
accepts_nested_attributes_for :people
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>]
As you can see the type
attributes is set to nil
instead of "Developer"
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Rails3 解决方案:attributes_protected_by_default 现在是一个类 -方法:
Solution for Rails3: attributes_protected_by_default in now a class-method:
几天前我遇到了类似的问题。 STI 模型中的继承列(即
type
)是受保护的属性。执行以下操作来覆盖Person
类中的默认保护。Rails 2.3
Rails 3
请参阅 解决方案 href="https://stackoverflow.com/users/188031/tokland">@tokland。
警告:
您正在覆盖系统受保护的属性。
参考:
关于该主题的问题
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 yourPerson
class.Rails 2.3
Rails 3
Refer to the solution suggested by @tokland.
Caveat:
You are overriding the system protected attribute.
Reference:
SO Question on the topic
上面的补丁对我不起作用,但这确实(Rails3):
Foo.bars.build(:type=>'Baz').class == Baz
Patches above did not work for me, but this did (Rails3):
Foo.bars.build(:type=>'Baz').class == Baz
对于我们这些使用 Mongoid 的人来说,您需要使
_type
字段可访问:For those of us using Mongoid, you will need to make the
_type
field accessible: