你需要設置你的模型是這樣的:
應用程序/模型/ account.rb
class Account < ActiveRecord::Base
has_many :organizations
accepts_nested_attributes_for :organizations
end
應用程序/模型/ organization.rb
class Organization < ActiveRecord::Base
has_many :people
accepts_nested_attributes_for :people
end
然後,您將在您的AccountsController
中設置new
動作,如下所示:
class AccountsController < ApplicationController
def new
@account = Account.new
organization = @account.organizations.build
person = @account.people.build
end
end
爲什麼?好了,因爲你設置的形式app/views/accounts/new.html.erb
這樣的:
<%= form_for(@account) do |account| %>
<%# account fields go here, like this: %>
<p>
<%= account.label :name %>
<%= account.text_field :name %>
</p>
<%# then organization fields, nested inside the account (which is what account represents) %>
<%# this will create a new set of fields for each organization linked to the account %>
<%= account.fields_for :organizations do |organization| %>
<p>
<%= account.label :name %>
<%= account.text_field :name %>
</p>
<%# and finally, people %>
<%= organization.fields_for :people do |person| %>
<p>
<%= person.label :name %>
<%= account.text_field :name %>
</p>
<% end %>
<% end %>
<% end %>
這些字段會那麼所有回傳給在AccountsController
的create
動作嵌套在params[:account]
。你對付他們這樣的:
class AccountsController < ApplicationController
def create
@account = Account.new(params[:account])
if @account.save
# do something here like...
redirect_to root_path, :notice => "Account created!"
else
#
flash[:error] = "Account creation failed!"
render :new
end
end
end
因爲你定義在Account
和Organization
車型都accepts_nested_attributes_for
,該PARAMS將被成功解析,當它創建帳戶,將創建組織,並將其鏈接到帳戶,然後創建該人員並將其鏈接到組織。
完成!
請提供表單結構,當前正在使用的控制器動作代碼和任何其他詳細信息(如,如果您使用的是accepted_nested_attributes_for)等 – clyfe