我跟着這個Rails tutorial描述如何做嵌套模型表單。在4:32,他開始描述如何用三個空模型預先填充表單。這兩種型號的問題是:Rails:沒有什麼產生3.times {model1.model2.build}
class Event < ActiveRecord::Base
has_many :positions, dependent: :destroy
accepts_nested_attributes_for :positions
end
而且......
class Position < ActiveRecord::Base
belongs_to :event
end
在我的事件控制器,我加入了教程的代碼爲new
方法
def new
@event = Event.new
3.times { @event.positions.build }
end
我的活動的形式視圖也被填充。
<!-- /apps/views/events/_form.html.erb -->
<%= form_for(@event) do |f| %>
<h3>Event Details</h3>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<!-- more fields here -->
<h3>Create positions for the event</h3>
<% f.fields_for :positions do |builder| %>
<p>
<%= builder.label :name %>
<%= builder.text_field :name %>
</p>
<!-- more fields here -->
<% end %>
<!-- more fields here -->
<% end %>
但是,position
字段沒有出現在我的表單上。我rake db:migrated
並重新啓動服務器(Ctrl-C
,rake s
)一堆次沒有效果。我究竟做錯了什麼?
是'@ event.positions.build'的方法? '@ event.positions.build()'怎麼樣? – Automatico
是一種ActiveRecord方法。在Ruby中你不需要()。 – cortex
railscast沒有parens。我添加了它們,並沒有影響任何東西。 – Jeff