0

我真的很难理解如何使用由第二个模型连接的模型创建嵌套表单。我在 SO 上查找了许多帖子 并尝试了很多方法,但无法弄清楚,尽管我想我快到了。

我正在尝试以一种形式创建订阅、客户和客户的地址,但到目前为止,我只设法创建了订阅和客户。我的地址有问题。

一个客户可以有很多订阅,但只有一个地址(暂时,无论如何)

我的(缩写)代码如下所示:

订阅.rb

class Subscription < ActiveRecord::Base

  belongs_to :customer
  has_one :address, through: :customer

  accepts_nested_attributes_for :customer, :address
  attr_accessible :customer_attributes, :address_attributes

客户.rb

class Customer < ActiveRecord::Base

  has_one :address
  has_many :subscriptions

  accepts_nested_attributes_for :address
  attr_accessible :address_attributes

地址.rb

class Address < ActiveRecord::Base

  belongs_to :customer
  has_many :subscriptions, through: :customer

订阅控制器.rb

def new
  @subscription = Subscription.new    
  customer = @subscription.build_customer
  address = customer.build_address
  subscription_line_items = @subscription.subscription_line_items.build
end

订阅/_form.html.erb

<%= form_for(@subscription) do |subscription_form| %>
  <% if @subscription.errors.any? %>
    <!-- Error stuff -->
  <% end %>

  <div class="field">
    <%= subscription_form.label :start_date %><br />
    <%= subscription_form.text_field :start_date %>
  </div>

  ...

  <h2>Customer Details</h2>
  <%= subscription_form.fields_for :customer do |customer_fields| %>
    <%= customer_fields.label :first_name %><br /> 
    <%= customer_fields.text_field :first_name %>
    ...
  <% end %>

  <h2>Address</h2>
  <%= subscription_form.fields_for :address do |address_fields| %>
    <%= address_fields.label :address_1 %><br /> 
    <%= address_fields.text_field :address_1 %>
    ...
  <% end %>

  <div class="actions">
    <%= subscription_form.submit %>
  </div>
<% end %>

我知道我的控制器代码正在工作,因为当我直接在控制台中尝试它时,我得到一个空地址对象,但这并没有以表单形式呈现,这让我相信我的模型代码仍然不正确.

4

1 回答 1

1

Purpletonic,查看您的最新问题:

Can't mass-assign protected attributes: customer, address

您需要在模型中添加这些属性,例如:

attr_accessible :customer, :address
于 2013-03-10T04:50:24.060 回答