0

2 番目のモデルで接続されたモデルを使用してネストされたフォームを作成する方法を理解するのに本当に苦労しています。私はSOに関する多く 投稿を調べ、多くのアプローチを試みましたが、ほとんどそこにいると思いますが、それを理解することはできません.

サブスクリプション、顧客、および顧客の住所を 1 つのフォームで作成しようとしていますが、これまでのところ、サブスクリプションと顧客しか作成できませんでした。アドレスに問題があります。

顧客は多くのサブスクリプションを持つことができますが、アドレスは 1 つだけです (とにかく、当分の間)。

私の(省略された)コードは次のようになります。

サブスクリプション.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

customer.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

subscriptions_controller.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 に答える