[英]Ruby on Rails: Accept nested attributes for parent rather than child records?
In my Rails app Users
can have many People
which in turn can (but don't have to) belong to Organisations
. 在我的Rails应用程序中,
Users
可以有很多People
,这些人又可以(但不必)属于Organisations
。
In short, this: 简而言之,这是:
Users --< People >-- Organisations
Now, it would be nice to be able to create new organisations from within a people view somehow. 现在,能够以某种人的视角在内部创建新组织将是一件很高兴的事情。 It tried this:
它尝试这样做:
class Person < ActiveRecord::Base
attr_accessible :name, :organisation_attributes
belongs_to :user
belongs_to :organisation
accepts_nested_attributes_for :organisation
end
But it's not working because Organisation is not a child of Person. 但这是行不通的,因为组织不是Person的孩子。
Is there another way to realise this? 还有另一种方法可以实现这一目标吗?
Thanks for any help. 谢谢你的帮助。
I can see that Person
is actually a child of Organisation
and its possible to make nested form for parent model also. 我可以看到
Person
实际上是Organisation
的子代,并且也可以为父模型创建嵌套形式。 And you are already using accepts_nested_attributes_for
. 并且您已经在使用
accepts_nested_attributes_for
。
Im assuming that you want to show a Organisation
form for a already saved person
. 我假设您想显示一个已经保存的
person
的Organisation
形式。 Then 然后
In your PeopleController#show
method build the organisation 在您的
PeopleController#show
方法中建立组织
@person.build_organisation
And in people/show.html.erb
并在
people/show.html.erb
form_for(@person) do |f|
f.fields_for(:organisation) do |fo|
# show the fields of organisation here.
end
end
It should work. 它应该工作。
Update: 更新:
I tried something similar and it worked :) Ive made a gist including the snippets. 我尝试了类似的方法,但效果很好:)我弄了包括摘要在内的要点。 Please follow the link https://gist.github.com/3841507 to see it working.
请点击链接https://gist.github.com/3841507,以查看它是否有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.