0
我真的很努力去理解如何創建一個嵌套窗體與第二個模型連接的模型。我擡頭看了一個numberofposts就這樣,並嘗試了很多方法,但無法弄清楚,儘管我認爲我幾乎在那裏。Rails與has_one通過關係嵌套窗體
我試圖創建一個訂閱,客戶和客戶的地址在一個表格中,但迄今爲止,我只設法創建訂閱和客戶。我的地址有問題。
顧客可以有很多訂閱,但只有一個地址(暫時的,反正)
我(略)的代碼如下所示:
subscription.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
address.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 %>
我知道我的控制器代碼工作,因爲當我嘗試直接在控制檯中,我得到一個空的地址對象,但是這並沒有被渲染到表單中,這導致我相信我的模型代碼仍然不正確。
從控制器的唯一變量將傳遞通過你的看法將是@subscription變量。您還需要創建其他實例變量。 – JosephL 2013-02-28 22:55:05
如果我更改爲控制器中的實例變量以及視圖中的fields_for,在提交'Can not mass-assign protected attributes:customer,address'時出現錯誤 – purpletonic 2013-03-01 08:23:58