嵌套资源到两个模型

时间:2011-12-12 22:56:36

标签: ruby-on-rails ruby associations

我有3个模型:帐户,组织和个人

Account 
  has many Organizations 
  has many People
Organization
  belongs to Account
  has many People
People
  belongs to Organization
  belongs to Account

这里的问题是,在以相同的形式创建新帐户,组织和人员时,如何将account_id和organization_id写入人员表?

1 个答案:

答案 0 :(得分:1)

您需要像这样设置模型:

应用/模型/ 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

然后,您将在new中设置AccountsController这样的行为:

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 %>

然后,这些字段将全部传回create嵌套在AccountsController内的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

由于您已在accepts_nested_attributes_forAccount模型中定义Organization,因此将成功解析参数并在创建帐户时创建组织和链接它到帐户,然后创建人并将其链接到组织。

完成!