nested_attributes(has_many:手机)的表格
Forms for nested_attributes (has_many: mobiles)
联系模特
class Contact < ActiveRecord::Base
belongs_to :phonebook
has_many :mobiles
accepts_nested_attributes_for :mobiles
end
手机模型
class Mobile < ActiveRecord::Base
belongs_to :contact
end
联系人控制器
def new
@contact = Contact.new
end
注:
- 移动模型具有详细信息和类型作为属性。
- 联系人模型将名称作为属性。
如何使用 rails 帮助器编写表单来为新的联系人实例生成多个移动对象?
这是我的表格
<h1>Create a new Contact</h1>
<h2>Add details</h2>
<% form_for(@contact) do |f| %>
<%= f.error_messages %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :mobile %><br />
<% f.fields_for :mobile do |ff| %>
<div>
<%= ff.select :type,options_for_select([["HOME", "H"], ["WORK", "W"],["OTHER", "O"]])%>
<%= ff.text_field :details %>
</div>
<% end %>
</div>
<div class="actions">
<%= f.submit "Add Contact" %>
</div>
<% end %>
看看here。您的控制器中需要这样的东西:
def new
@contact = Contact.new
2.times { @contact.mobiles.build}
end
关于 build
的解释可以在 API docs:
中找到
build(attributes = {}, &block) Link
Returns a new object of the collection type that has been instantiated
with attributes and linked to this object, but have not yet been
saved. You can pass an array of attributes hashes, this will return an
array with the new objects.
更新
如果您想动态添加字段,请查看:
- Adding dynamic fields to nested form through AJAX
- https://github.com/lailsonbm/awesome_nested_fields
联系模特
class Contact < ActiveRecord::Base
belongs_to :phonebook
has_many :mobiles
accepts_nested_attributes_for :mobiles
end
手机模型
class Mobile < ActiveRecord::Base
belongs_to :contact
end
联系人控制器
def new
@contact = Contact.new
end
注:
- 移动模型具有详细信息和类型作为属性。
- 联系人模型将名称作为属性。
如何使用 rails 帮助器编写表单来为新的联系人实例生成多个移动对象?
这是我的表格
<h1>Create a new Contact</h1>
<h2>Add details</h2>
<% form_for(@contact) do |f| %>
<%= f.error_messages %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :mobile %><br />
<% f.fields_for :mobile do |ff| %>
<div>
<%= ff.select :type,options_for_select([["HOME", "H"], ["WORK", "W"],["OTHER", "O"]])%>
<%= ff.text_field :details %>
</div>
<% end %>
</div>
<div class="actions">
<%= f.submit "Add Contact" %>
</div>
<% end %>
看看here。您的控制器中需要这样的东西:
def new
@contact = Contact.new
2.times { @contact.mobiles.build}
end
关于 build
的解释可以在 API docs:
build(attributes = {}, &block) Link
Returns a new object of the collection type that has been instantiated with attributes and linked to this object, but have not yet been saved. You can pass an array of attributes hashes, this will return an array with the new objects.
更新
如果您想动态添加字段,请查看:
- Adding dynamic fields to nested form through AJAX
- https://github.com/lailsonbm/awesome_nested_fields