[英]Rails 4 Nested form has_many through association and database
所以我有三个模型客户端,地址和地址信息。 但是,当我为address和address_info创建一个嵌套表单时,我得到的行基本上是我想要的两倍。 前三行将具有绑定的addresstype和clientid,其他三行将具有与其绑定的clientid和addressid。 这是输出示例:
如您所见,这些行没有与该行关联的地址和客户端ID。 我不确定该如何解决。
这是我的模型:
#client model
has_many :address_infos
has_many :addresses, through: :address_infos
accepts_nested_attributes_for :addresses, :address_infos, reject_if: :all_blank, allow_destroy: true
#addressinfo model
belongs_to :client
belongs_to :address
#address model
has_many :address_infos
has_many :clients, through: :address_infos
这是我的客户控制器:
def new
@client = Client.new
@client.address_infos.build
@client.addresses.build
end
def create
@client = Client.new(client_params)
end
private
def client_params
params.require(:client).permit(:firstname, :middlename, :lastname,
addresses_attributes: [:street, :city, :state, :zipcode],
address_infos_attributes: [:ownorrent, :addresstype, :yearsofresidency])
end
end
这是我的观点,请注意,对于邮件和以前的地址,我也没有嵌套的表格:
<%= form_for(@client) do |f| %>
<%= f.fields_for :addresses do |addresses_form| %>
<!-- misc. code -->
<%= f.fields_for :address_infos do |addressinfo_form| %>
<%= addressinfo_form.label :ownorrent, "Own", :value => "Own" %>
<%= addressinfo_form.radio_button :ownorrent, :own %>
<%= addressinfo_form.label :ownorrent, "Rent", :value => "Rent" %>
<%= addressinfo_form.radio_button :ownorrent, :rent %>
<%= addressinfo_form.text_field :yearsofresidency, class:"form-control", id:"inputfield", placeholder:"Years" %>
<%= addressinfo_form.text_field :addresstype,:value => "presentaddress" %>
<% end %>
<% end %>
更新因此,在执行了建议的操作之后,我最终在数据库中添加了该地址:我尝试添加的地址是123 Fake St的地址。其他内容直接植入了种子。 address_id仍然与其余内容不符。 我还更新了当前模型。
在保存到数据库之前,应该控制嵌套属性。 使用reject_if
或allow_blank
选项可防止和销毁空白记录。
accepts_nested_attributes_for :addresses, :address_infos, reject_if: :all_blank, allow_destroy: true
有关控制参数的更多选项,请访问链接http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.