[英]How to construct form_for in Rails that can create both belongs_to and has_many association
I have a has_many and belongs_to
association in my Rails app.我的 Rails 应用中有has_many and belongs_to
关联。 An OfficeAddress
belongs_to Address
, so my problem right now is how to build it on the form.一个OfficeAddress
Address
,所以我现在的问题是如何在表单上构建它。 When I create a new office address, to associate it into my address, the address should be created already.当我创建一个新的办公地址时,要将其关联到我的地址,该地址应该已经创建。 On my office_address_controller
I have this.在我的office_address_controller
我有这个。
class OfficeAddressesController < ResourceController
def index
@office_address = Spree::OfficeAddress.all
end
def new
new_address = Spree::Address.new
@new_office_address = new_address.office_address.build
end
def create
p params
end
end
and on my office address new.html.erb
is currently empty because I can't find any documentation on how to build a form.在我的办公室地址new.html.erb
目前是空的,因为我找不到任何关于如何构建表单的文档。 I'd be interested in examples or documentation.我会对示例或文档感兴趣。 Also the controller build
confuses me.控制器build
也让我感到困惑。 It didn't throw any error I was expecting error as new_address
doesn't have any Id yet.它没有抛出任何我期望的错误,因为new_address
还没有任何 Id。
So I don't know if this is the right answer but this works for me.所以我不知道这是否是正确的答案,但这对我有用。 So here's my code.所以这是我的代码。
Controller:控制器:
def new
@new_office_address = Spree::OfficeAddress.new
end
def create
b = Spree::Address.create(permit_params_address)
c = Spree::OfficeAddress.create(address_id: b.id)
if b.save && c.save
redirect_to admin_office_addresses_path
else
p b.errors.messages
end
end
View, new.html.erb查看,new.html.erb
<%= form_for [:admin, @new_office_address], html: { autocomplete: "off" } do |ofc_add_form| %>
<fieldset data-hook="new_property">
<div class="row">
<div class="col-md-12">
<%= fields_for :address, Spree::Address.default do |adds|%>
<%= render :partial => 'spree/admin/shared/address_form', :locals => { :f => adds, :type => "New Office Address" } %>
<%end%>
</div>
</div>
<div class="form-actions">
<%= render partial: 'spree/admin/shared/new_resource_links' %>
</div>
</fieldset>
<% end %>
I was doing the right thing at first but I forgot to Spree::Address.default
on fields_for
I don't really know what it does but on the rails syntax, it accepts an object.一开始我是在做正确的事情,但我忘了在fields_for
上fields_for
Spree::Address.default
, fields_for
我真的不知道它是做什么的,但在 Rails 语法上,它接受一个对象。
on my controller new
method, after creating the address, to relate them with each other (OfficeAdddress) I just grab the Id from the address that was created and add it on my office address.在我的控制器new
方法上,创建地址后,将它们相互关联 (OfficeAdddress) 我只需从创建的地址中获取 Id 并将其添加到我的办公室地址中。 I'm not sure this is the best way to solve the problem.我不确定这是解决问题的最佳方法。 I'm open for changes.我愿意接受改变。 I'm also adding more validation on my new method我还在我的新方法上添加更多验证
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.