我正在尝试在company#show页面上使用嵌套表格向一家公司添加地址。我可以成功添加新地址,但是在重新加载页面时,新地址的表单区域将填充现有记录。
我如何仅显示空的已建记录,而不显示现有记录?
这是在表单区域中显示的内容...
这就是我所期望的...
这是公司#显示页面...
= form_for @company do |f|
= f.fields_for :addresses do |t|
.form-inline
.col-md-2
= t.text_field :street1, class: 'form-control form-control-sm', placeholder: 'Street 1', id: 'street1'
.col-md-2
= t.text_field :street2, class: 'form-control form-control-sm', placeholder: 'Street 2', id: 'street2'
.col-md-2
= t.text_field :apt_other, class: 'form-control form-control-sm', placeholder: 'Suite #', id: 'apt_other'
.col-md-2
= t.text_field :city, class: 'form-control form-control-sm', placeholder: 'City', id: 'city'
.col-md-1
= t.collection_select :state_id, @states, :id, :state_abbr, {:include_blank => 'State'} , {:class => 'form-control form-control-sm'}
.col-md-2
= t.text_field :zip, class: 'form-control form-control-sm', placeholder: 'Zip', id: 'zip'
.form-inline
.col-md-2
= t.text_field :phone, class: 'form-control form-control-sm', placeholder: 'Phone', id: 'phone'
.col-md-2
= t.text_field :fax, class: 'form-control form-control-sm', placeholder: 'Fax', id: 'fax'
.form-group-row
.text-center
.btn-group{role: 'group'}
= f.submit 'Save', class: 'btn btn-outline-success btn-sm', style: 'margin-bottom: .5em;'
答案 0 :(得分:0)
如果希望将其分开,则需要添加检查或条件以仅在fields_for中显示非持久性地址,或者需要在控制器中初始化新地址并仅显示该地址的表单。例如:
(typeaheadOnSelect)
然后不显示#companies_controller.rb
...
def show
@company = Company.find(params[:id])
@new_address = @company.addresses.build()
end
...
,而应该创建一个fields_for :addresses
我认为您也可以像这样将form_for @new_address
直接传递到@new_address
中:
fields_for
我还没有测试过,您可能需要将其写为数组= f.fields_for :addresses, @new_address do |t|
。这样做的主要目的是强制将特定的对象集合用于嵌套的[@new_address]
。您还可以阅读docs on fields_for。
答案 1 :(得分:0)
我将回答它以关闭线程。
这行是错误的。
= f.fields_for :addresses do |t|
这就是我将其更改为的
= f.fields_for :addresses, Address.new do |t|