Ruby on Rails:接受父级而不是子级记录的嵌套属性?
问题描述:
在我的Rails应用程序Users
可以有许多People
这反过来可以(但不必)属于Organisations
。Ruby on Rails:接受父级而不是子级记录的嵌套属性?
总之,这样的:
Users --<People>-- Organisations
现在,这将是很好,能够从内部人视图莫名其妙地创造新的组织。它试图这样做:
class Person < ActiveRecord::Base
attr_accessible :name, :organisation_attributes
belongs_to :user
belongs_to :organisation
accepts_nested_attributes_for :organisation
end
但它不工作,因为组织不是人的孩子。
有没有另一种方法来实现这一点?
感谢您的任何帮助。
答
我可以看到,Person
实际上是Organisation
的孩子,它也可能为父模型制作嵌套窗体。而且您已经在使用accepts_nested_attributes_for
。
我假设你想显示Organisation
表格已存储person
。然后
在你PeopleController#show
方法构建组织
@person.build_organisation
而且在people/show.html.erb
form_for(@person) do |f|
f.fields_for(:organisation) do |fo|
# show the fields of organisation here.
end
end
它应该工作。
更新:
我想类似的东西,它的工作:)我表现的包括片段梗概。 请按照链接https://gist.github.com/3841507看到它的工作。
请让我知道它的工作原理,同时即时通讯试图在我的机器上创建一个类似的场景......很好的问题btw。 – Samiron
感谢Samiron!看起来非常好。我需要几天的时间来研究这些代码,因为我对Rails还是一个新手。 – Tintin81
确定让我知道任何混乱。 – Samiron